Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: declare a class variable to be a stdClass object

This is probably pretty simple but I haven't been able to figure out how to phrase the question for Google, so here goes:

So, I often do something like this...

class foo {
    private $bar = array();
}

... to set some class property to be an array. However, I'd like to make a private property an object instead, something like this:

class foo {
    private $bar = new stdClass();
}

I tried several variations of this and none of them worked. Can this be done? For bonus points can you assign a private property to be any other class of object?

Thanks!

like image 955
Andrew Avatar asked Sep 29 '10 05:09

Andrew


1 Answers

You can't use functions (including constructors) in class member declarations. Instead set it up in the constructor for the class.

class Foo {

  private $bar;

  private $baz;

  public function __construct() {

    $this->bar = new stdClass();
    $this->baz = new Bat();

  }

  public function __get($key) {
      if(isset($this->$key) {
        return $this->$key;
      }

      throw new Exception(sprintf('%s::%s cannot be accessed.', __CLASS__, $key));
  }

}


$foo = new Foo();

var_dump($foo->bar);
var_dump($foo->bat);

And when you extend the class and need to override the constructor but still want the stuff in the parent classes constructor:

class FooExtended
{
   protected $coolBeans;

   public function __construct() {

      parent::__construct(); // calls the parents constructor

      $this->coolBeans = new stdClass();
   }
}

$foo = new FooExtended();

var_dump($foo->bar);
var_dump($foo->bat);
var_dump($foo->coolBeans);

It should also be noted this has nothing to do with visibility of the property... it doesn't matter if its protected, private, or public.

like image 181
prodigitalson Avatar answered Sep 19 '22 02:09

prodigitalson