Naveen Gupta
Naveen Gupta

Reputation: 286

Can we only define anonymous function inside constructor of class?

<?php 
class Foo
{
    public $bar;
    public $var;

    public function __construct() {
        $this->bar = function() {
            return 42;
        };
    }

    public function test(){
        $this->var = function() {
            return 44;
        };
    }
}

$obj = new Foo();
echo ($obj->bar)(), "<br/>";
var_dump($obj->test());

?>

Output: 42
NULL

Where i am doing wrong I want to get var value inside test function which 44.

Thanks in advance for your answer.

Upvotes: 0

Views: 174

Answers (1)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

With this method call $obj->test(), you're just assigning a function to the instance variable $var. And that's why when you do var_dump($obj->test());, it shows NULL because the method doesn't return anything.

Instead what you can do is, return $this from test() method and use the current instance to call that anonymous function, like this:

class Foo{
    public $bar;
    public $var;

    public function __construct() {
        $this->bar = function() {
            return 42;
        };
    }

    public function test(){
        $this->var = function() {
            return 44;
        };
        return $this;
    }
}

$obj = new Foo();
echo ($obj->bar)(), "<br/>";
echo ($obj->test()->var)();

Here's the demo.

Upvotes: 2

Related Questions