How to call non-static method from static method o

2020-05-19 02:16发布

I am working on PHP code.

Here is the sample code to explain my problem:

class Foo {

    public function fun1() {
             echo 'non-static';   
    }
    public static function fun2() {
        echo "static" ;
        //self::fun1();
        //Foo::fun1(); 
    }
}

How can I call the non-static method from the static method ?

Note: Both functions are used throughout the site, which is not known. I can't make any changes in the static/non-static nature of them.

标签: php oop
3条回答
混吃等死
2楼-- · 2020-05-19 02:48

Asnwer selcted as correct solves problem. There is a valid use case (Design Pattern) where class with static member function needs to call non-static member function and before that this static members should also instantiate singleton using constructor a constructor.

Case: For example, I am implementing Swoole HTTP Request event providing it a call-back as a Class with static member. Static Member does two things; it creates Singleton Object of the class by doing initialization in class constructor, and second this static members does is to call a non-static method 'run()' to handle Request (by bridging with Phalcon). Hence, static class without constructor and non-static call will not work for me.

查看更多
疯言疯语
3楼-- · 2020-05-19 02:53

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

查看更多
甜甜的少女心
4楼-- · 2020-05-19 02:54

The main difference would be that you can call static methods for a class without having to instantiate an object of that class. So, in your static method try

Foo $objInst = new Foo();
$objInst->fun1();

But I don't see how this would make any sense in any context.

查看更多
登录 后发表回答