1

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?

Run
  • 54,938
  • 169
  • 450
  • 748

3 Answers3

2

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.

Ruben Serrate
  • 2,724
  • 1
  • 17
  • 21
1
$page->hasChidren->setId(10);
var_dump(page->hasChidren->getID();
po_taka
  • 1,816
  • 17
  • 27
1

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

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126