gpt4 book ai didi

php - 如何从同一个类的静态方法调用非静态方法?

转载 作者:IT王子 更新时间:2023-10-29 01:23:56 25 4
gpt4 key购买 nike

我正在研究 PHP代码。

这是解释我的问题的示例代码:

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.

最佳答案

您必须在静态方法中创建一个新对象才能访问该类中的非静态方法:

class Foo {

public function fun1()
{
return 'non-static';
}

public static function fun2()
{
return (new self)->fun1();
}
}

echo Foo::fun2();

结果将是非静态

稍后编辑:鉴于对将变量传递给构造函数的兴趣,我将发布该类的更新版本:

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

关于php - 如何从同一个类的静态方法调用非静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41631623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com