Tutorial :Arrays as objects



Question:

I there a method to allow me to use an array as an object?

I have the following code in my main class

function  __construct()  {          require 'config.php';          $this->config = new PHPSO_Config();  }  

where the PHPSO_Config class looks something like this

class PHPSO_Config  {      /**       * The administrators email address       */      var $adminEmail = 'user@domain.tld'; //I'm using this email to test  }  

so can I accomplish the same thing and be able to access the config vars as an object without creating a second class?


Solution:1

You can cast an array to an object using

$myObject = (object) $myarray;  

thus the following should work (untested):

function  __construct()  {          require 'config.php';          $this->config = (object) array("username" => "root");  }  

then $class->config->username should work.


Solution:2

You could use PHP5 overloading to make it seem that your class has the properties provided by the config class, e.g. something like this:

class MyClass  {      private $config;        function  __construct()      {          require 'config.php';          $this->config = new PHPSO_Config();      }          public function __get($name) {          if (property_exists($this->config, $name)) {              return $this->config->$name;          }          return null;  }  

Then doing something like this:

$config=new MyClass;  echo $config->adminEmail;  

Would result in seeing the adminEmail member variable of the internal config class.

This is almost a Strategy Pattern, where the runtime implementation of a class can be selected at runtime.


Solution:3

I'm not sure exactly what you want, but you can cast an array to an object. Make sure you don't use numeric indices though as they don't work quite right;

$config = array('adminEmail' => 'user@domain.tld');  $this->config = (object)$config;  


Solution:4

Maybe I am missing something here but are you trying to replace your config class with an array, then cast it to an object? Sounds a little crazy to me. I would just have a config class, its way better design.

Its best not to go around making arrays where you should have classes.


Solution:5

Well yeah

there are a technique that personally I would use it:

you create a file call whatever you want (i.e. config.php) then write this in it forexample:

Whenever you wanted use these information you have to just put "require_once "config.php";" above your code like in index.php and all definition will be in that page. For example you can read database server name by typing $DB_SERVER.

If I were you I would stick to it because you can use it everywhere in your project and maintain it just from a file which makes life easier.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »