Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Multiple Object Dereference

Tags:

php

How can I do multiple levels of de-referencing? For instance, in C#, we can keep appending a '.' to access the next objects properties: string s, s.ToString(), s.ToString().ToUpper(). With PHP, I get to around $this->someobject, but $this->someobject->somethingelse does not appear to work.

Any ideas?

like image 751
user978122 Avatar asked Feb 24 '26 11:02

user978122


2 Answers

Assuming you're using PHP5+, and $this->someobject returns an object with a property called somethingelse; it should work.

Similarly, this also works

class Example
{
    public function foo()
    {
        echo 'Hello';
        return $this; // returning an object (self)
    }

    public function bar()
    {
        echo ' World';
        return $this;
    }
}

$example = new Example;
$example->foo()->bar(); // Hello World
$example->foo()->foo()->foo()->bar()->foo(); // HelloHelloHello WorldHello

Edit:

Just as a further note, you don't have to return self. Any object will suffice.

class Example1
{
    public function __construct(Example2 $example2)
    {
        $this->example2 = $example2;
        $this->example2->setExample1($this);
    }

    public function foo()
    {
        echo 'Hello';
        return $this->example2;
    }
}

class Example2
{
    public function setExample1(Example1 $example1)
    {
        $this->example1 = $example1;
    }

    public function bar()
    {
        echo ' World';
        return $this->example1;
    }
}

$example = new Example1(new Example2());
$example->foo()->bar(); // Hello World
$example->foo()->bar()->foo()->bar(); // Hello WorldHello World
like image 96
adlawson Avatar answered Feb 27 '26 01:02

adlawson


PHP's dereference operator only works on Objects; and, unlike some other languages, only Objects are objects ;) Primitives don't have an implicit wrapper. So, if $this->someobject resolves to a non object, (like a string, float, int or array), you cannot chain the dereference operator any further.

like image 35
Shad Avatar answered Feb 26 '26 23:02

Shad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!