Note that there are some explanatory texts on larger screens.

plurals
  1. POphp class do once for all instances
    primarykey
    data
    text
    <p>So I have a class whose constructor downloads some xml and reads it into properties for the class to work with. I'm instantiating this class a couple of times and this time-consuming job is done three times in exactly the same manner. Could I avoid it somehow (I guess with a static method/properties)? My class should only once go get the properties and then every instance could use them. I feel I should put the code out of my constructor in a static function, but how it's done exactly, I don't know, since I always get errors.</p> <pre><code>class MyClass { protected $xml_file; protected $xml_derived_array; public function __construct($param1, $param2, $param3) { //get xml_file and make xml_derived_array with it //do some other stuff with parameters and properties such as $xml_derived_array } } </code></pre> <p>Should become something like: (but how should I call the static properties in my __construct and how should I set the properties in the static function?)</p> <pre><code>class MyClass { protected static $xml_file; protected static $xml_derived_array; protected static function get_xml() { //get xml_file and make xml_derived_array with it (?how exactly?) } public function __construct($param1, $param2, $param3) { self::get_xml(); //do some other stuff with parameters and properties such as $xml_derived_array (?how exactly?) } } </code></pre> <p><strong>Edit</strong> This is how it is now working:</p> <pre><code>class MyClass { protected static $xml_file; protected static $xml_derived_array = array(); public function __construct($param1, $param2, $param3) { if (!self::$xml_file) { self::$xml_file = simplexml_load_file('xml_file.xml'); self::$xml_derived_array[0] = self::$xml_file-&gt;title; } echo self::$xml_derived_array[0].$param1; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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