Goodnight !

Completely confused.

There is a class:

class Test { function index() { echo 'Test-index'; } function test() { echo 'Test-test'; } } 

and function

  function load($class, $method) { //допустим $class = 'Test', $method = 'index' ($method = 'index()' тоже пробовал) $test = new $class; // $test->index() работает $test->$method; // не работает Undefined property: Test::$index } 

How can it be correctly called?

    2 answers 2

    Perhaps you had to enter this:

     class Test { public function testMethod() { echo 'called!'; } } $t = new Test(); $methodName = 'testMethod'; $t->$methodName(); 

    If there is no - this kind of behavior is not standard for PHP, in order to be able to do this, you need to save an anonymous function in the class field, for example (PHP 5.3+):

     class Test { public $testPropertyMethod; public function __construct() { $this->testPropertyMethod = function() { echo 'Hello closure'; }; } } $t = new Test(); $fieldName = 'testPropertyMethod'; $func = $t->$fieldName; $func(); 

    But there is one thing here - by applying this approach calling a code of the form:

     $t->$fieldName(); // выбросит ошибку 

    In order for the call to work correctly and in this case, it is necessary to determine (it sounds stupid, but I did not invent it) the "magic" __call method in our class, something like:

     public function __call( $methodName, $arguments ) { $func = $this->$methodName; return call_user_func_array($func, $arguments); } 

    Now absolutely everything will work exactly as expected.

    PS: A little help: $ an is not available in anonymous functions (although if necessary, of course, we can pass it on our own).

    • That's what you need, $ t -> $ methodName (); It works as it should. I did not notice that I did not put the brackets :). Thank. - Sever
      $test->$method(); 
    • Thank you for what you need! Just unfortunately, I can take for the correct only 1. :( - Sever
    • @FLK - an interesting feature of php 5.4 has been since the fourth version: D In the fourth, the designers were determined that way, then they invented __construct, but the old approach is supported further for compatibility - Zowie