如何从同一个类的静态方法中调用非静态方法? [英] How to call non-static method from static method of same class?

查看:1039
本文介绍了如何从同一个类的静态方法中调用非静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 PHP 代码.

以下是用于说明我的问题的示例代码:

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(); 
    }
}

如何从静态方法调用非静态方法?

注意:这两个功能在整个站点中都使用,这是未知的.一世 不能对它们的静态/非静态性质进行任何更改.

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.

推荐答案

您必须在static方法内创建一个新对象,以访问该类内的非静态方法:

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();

结果将为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');

结果将是foo - bar

这篇关于如何从同一个类的静态方法中调用非静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆