0

I want to know is it possible to have a class that's extended have a var set and used from the base class?

eg:

class me
{
    public $hello = array();

    protected function setter($me)
    {
        $this->hello[] = $me;
    }
}

class foo extends me
{
    public function __construct()
    {
        $this->setter('foo');
    }
}

class yoo extends me
{
    public function __construct()
    {
        parent::setter('yoo');
    }
}

$me = new me();
$foo = new foo();
$yoo = new yoo();

print_r($me->hello);

the array printed is array() nothing is set.

1
  • It seems that what you are trying to do here is not set a var on the base class but set a var on an instance of the base class. The class me may be the base for the classes foo and yoo but the object $me is not the base of anything. Commented May 29, 2012 at 1:11

2 Answers 2

1

Yes, you can do this by making $hello static:

public static $hello = array();

In doing so, you will have to drop the $this from $this->hello[] = $me; and replace it with a self, as hello will not longer be unique to the current object instance:

self::$hello[] = $me;
Sign up to request clarification or add additional context in comments.

2 Comments

Cool and all I do is make a getter that does return self::$hello;
This is correct, but keep in mind that there will now be only one $hello for all instances of me and all of its subclasses.
0

You were using

parent::setter('yoo');

But in parent class me, that function is not defined as static. So you cannot use :: to call un-static function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.