Call static method with class name stored as instance variable

前端 未结 2 415
逝去的感伤
逝去的感伤 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: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.

提交回复
热议问题