Call static method with class name stored as instance variable

前端 未结 2 414
逝去的感伤
逝去的感伤 2021-01-25 18:33

Consider this script

class B
{
    static public function hi() { echo \"hi\\n\"; }
}
class A
{
    private $name = \'B\';

    public function __construct()
             


        
相关标签:
2条回答
  • 2021-01-25 19:21

    The current implementation of Zend PHP parser supports only static method calls that are made directly on a class name or a variable. Here is the grammar:

    %token T_PAAMAYIM_NEKUDOTAYIM ":: (T_PAAMAYIM_NEKUDOTAYIM)"
    
    function_call:
        name argument_list
            { $$ = zend_ast_create(ZEND_AST_CALL, $1, $2); }
    |   class_name T_PAAMAYIM_NEKUDOTAYIM member_name argument_list
            { $$ = zend_ast_create(ZEND_AST_STATIC_CALL, $1, $3, $4); }
    |   variable_class_name T_PAAMAYIM_NEKUDOTAYIM member_name argument_list
            { $$ = zend_ast_create(ZEND_AST_STATIC_CALL, $1, $3, $4); }
    |   callable_expr argument_list
            { $$ = zend_ast_create(ZEND_AST_CALL, $1, $2); }
    

    Source: https://github.com/php/php-src/blob/master/Zend/zend_language_parser.y#L890

    0 讨论(0)
  • 2021-01-25 19:26

    Given that in your current circumstances you require a method of the class b within the class a, it seems pretty anti intuitive to approach it this way. Further, the the availability to call a method of another class is simply not there, you would need to use:

    call_user_func(array($this->name, 'hi'));
    

    one way is to simply require the B class as a depency of the constructor function of the A class:

    class B
    {
        static public function hi() { echo "hi\n"; }
    }
    
    class A
    {
        private $b;
    
        public function __construct(B $b)
        {
    
            $b::hi();
    
        }
    }
    new A(new B);
    

    This is probably as close to the one liner approach that you're looking for that you can get.

    0 讨论(0)
提交回复
热议问题