Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to store a function in PHP object's properties? [duplicate]

Tags:

php

Is it possible to store a function in PHP object's properties like this:

class testing {
    public $testvars;
    function __construct(){
        $this->testvars = function(){
            return "Test String";
        };
    }
}

If it's possible, how do you call it?

I have been trying to call it like this:

$main = new testing();
$main->testvars();

But it throws an error:

Fatal error: Call to undefined method testing::testvars()
like image 719
Ikhsan Bahar Avatar asked Sep 05 '25 01:09

Ikhsan Bahar


1 Answers

Try to call like

$this->testvars();

Considering that you are calling this function in the same class.And if you are calling this in another class you need to add this _call() function

public function __call($method, $args) {
   if(isset($this->$method) && is_callable($this->$method)) {
       return call_user_func_array(
           $this->$method, 
           $args
       );
   }
}

to your new class and you can call it as

$main->testvars();
like image 182
Gautam3164 Avatar answered Sep 07 '25 15:09

Gautam3164