views:

41

answers:

1

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!

+4  A: 

You cant 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 doesnt matter if its protected, private, or public.

prodigitalson
Ok, that works. However, what if I want this class to be extendable by other classes which may override the constructor? Is there a way to ensure that $bar stays an object?
Andrew
see my notes edits... and also review the Classes and Objects Manual: http://php.net/manual/en/language.oop5.php
prodigitalson
Thanks for the extended example, I see how you did it. I wish that you could simply declare something to be an object the way you can declare it to be an array. This would allow me to "fool-proof" the code better: I don't like requiring users to call the parent constructor because they seem to always forget and not be able to figure out why things aren't working. However, sometimes you gotta do what you gotta do. Thanks for the help!!
Andrew
Most people will know to do that... Id they dont then they dont know OOP PHP very well and so its not really your fault :-) Further more you could add getters that create the object if it isnt already initalized...
prodigitalson
when you extend the parent class, all the child class should get your stdclass object, if you don't want other people to override it, you can declared it as private in parent class, then using "final" keyword for object variable's getter and setter, so the $bar will stay as an object, hope this helps.
vito huang