Question

I am trying to get a result from a chaining method from extended classes below,

class Base
{
    protected $id;

    public function setId($input) {

        $this->id = $input;

        return $this;
    }
}

class PageChildren extends Base
{
    public function getID()
    {
        return $this->id;
    }
}


class Page extends Base
{
    public $hasChidren;

    public function __construct()
    {
        $this->hasChidren = new PageChildren();
    }
}

$page = new Page();
var_dump($page->setId(10)->hasChidren->getID());

But I get null instead of 10. What shall I do to get it right?

Was it helpful?

Solution 2

$page->hasChidren->setId(10);
var_dump(page->hasChidren->getID();

OTHER TIPS

You are getting the ID of hasChidren, which is a new object of type PageChildren whose ID has never been set, you are not accessing the original object of type base to which you set the ID

You create a page object, when you create it one of his attributes contains a PageChildren object. Then you set the ID of your page object. And in the end you are getting the ID from the PageChildren object, not the Page object.

You are getting NULL since, when you do a

$page = new Page();

your constructor will run first which has the getID() method. The getID() method does not have anything to return and thus you get a NULL

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top