How to call non-static method from static method of same class?

后端 未结 3 1560
暗喜
暗喜 2021-01-31 07:36

I am working on PHP code.

Here is the sample code to explain my problem:

class Foo {

    public function fun1() {
             echo \'non-static\';   
         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-31 08:12

    You must create a new object inside the static method to access non-static methods inside that class:

    class Foo {
    
        public function fun1()
        {
            return 'non-static';
        }
    
        public static function fun2()
        {
            return (new self)->fun1();
        }
    }
    
    echo Foo::fun2();
    

    The result would be non-static

    Later edit: As seen an interest in passing variables to the constructor I will post an updated version of the class:

    class Foo {
    
        private $foo;
        private $bar;
    
        public function __construct($foo, $bar)
        {
            $this->foo = $foo;
            $this->bar = $bar;
        }
    
        public function fun1()
        {
            return $this->foo . ' - ' . $this->bar;
        }
    
        public static function fun2($foo, $bar)
        {
            return (new self($foo, $bar))->fun1();
        }
    }
    
    echo Foo::fun2('foo', 'bar');
    

    The result would be foo - bar

提交回复
热议问题