Note that there are some explanatory texts on larger screens.

plurals
  1. POphp define class within class (or next best thing)
    text
    copied!<p>I am aware that a class cannot be defined within a class in php, however I'm curious if there's another way to achieve the desired effect.</p> <p>I currently have a set of 3 objects used to conduct a search. The first is called $search_request. It contains properties like $keywords (string), $search_results_per_page (int), $page_requested (int), $owner_id (int)</p> <p>I also have an object called $search_result, it contains properties like $total_matches (int), $result_set (array of objects)</p> <p>Finally I have the $search_handler object which contains the $search_request and $search_result, along with functions that build the $search_result based on the $search_request. Usage goes like so:</p> <pre><code>$search_handler = new search_handler(); $search_handler-&gt;search_request-&gt;keywords = "cats, dogs"; $search_handler-&gt;search_request-&gt;search_results_per_page = 10; $search_handler-&gt;search_request-&gt;page_search_requested = 1; $search_handler-&gt;get_search_result(); echo $search_handler-&gt;search_result-&gt;total_matches; foreach($search_handler-&gt;search_result-&gt;result_set) { //do something } </code></pre> <p>All of this works fine. The problem is I want to repeat this model for different objects, so currently I'm forced to use the hackey solution of the "search_" prefix on each class.</p> <p>I'd like to have something like:</p> <pre><code>class search { public class request { $keywords = ""; $search_results_per_page = 5; $page_requested = 1; } public class result { $total_matches = null; $result_set = array(); } public get_results() { //check cache first $cached = look_in_cache(md5(serialize($this-&gt;request))); if($cached) { $this-&gt;result-&gt;result_set = $cached; $count = count($cached); $this-&gt;result-&gt;total_matches = $count; } else { //look in db $results = get_results_from_database($this-&gt;request-&gt;keywords); //db call goes here $this-&gt;result-&gt;result_set = $results; $count = count($results); $this-&gt;result-&gt;total_matches = $count; } } } //usage $search = new search(); $search-&gt;request-&gt;keywords = "cats, dogs"; $search-&gt;request-&gt;search_results_per_page = 10; $search-&gt;request-&gt;page_search_requested = 1; $search-&gt;get_results(); echo $search-&gt;results-&gt;total_matches; foreach($search-&gt;results-&gt;result_set as $result) { //do something } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload