Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Class member access on instantiation

Tags:

oop

php

I have a problem with the new syntax of PHP 5.4 My code with member access on instantiation

$oClass = (new Foo)->bar();
$oClass->bar2();

I get this error

Fatal error: Call to a member function bar2() on a non-objec

Why?

EDIT: I added return $this; in the method Foo::bar() and now it works

like image 794
Jérémy Dupont Avatar asked May 04 '26 10:05

Jérémy Dupont


1 Answers

My guess is that you think $oClass will contain an object. This is not the case; it contains the result of the function bar().

If you want to access bar2() you need to do the following as normal:

$oClass = new Foo;
$oClass->bar();
$oClass->bar2();

Class member access on instantiation is for when you only need to access a single member of the object breifly, and then you do not need the object any more.

Edit:
I've possibly overlooked something.

Consider the following code:

class Test {
    public function foo() {
        return $this;
    }

    public function bar() {
        return 'oh hai';
    }
}

$t = (new Test)->foo();

print $t->bar();

In this case you will still be able to access the object, because the function foo() returns $this and you are storing it, maintaining the reference to the object.

If you really want to, you can also chain methods like so:

print (new Test)->foo()->bar();
like image 55
Leigh Avatar answered May 05 '26 23:05

Leigh



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!