gpt4 book ai didi

php - 通过对象调用静态方法是不好的做法吗?

转载 作者:可可西里 更新时间:2023-10-31 23:13:19 25 4
gpt4 key购买 nike

<分区>

我发现在某些用例中通过对象调用静态方法会非常方便。

我想知道这是否被视为不良做法?

或者这个特性是否会在未来的 PHP 版本中被移除?

class Foo
{
public static function bar ()
{
echo 'hi';
}
}

class SubFoo extends Foo
{
public static function bar ()
{
echo 'hi subfoo';
}
}

// The normal way to call a static method.
Foo::bar(); // => "hi"

// Call the static method via instance.
$foo = new Foo;
$foo::bar(); // => "hi"


// Here is the use case I found calling static method via instance is convenient.
function callbar(Foo $foo)
{
// The type-hinting `Foo` can be any subclass of `Foo`
// so I have to figure out the class name of `$foo` by calling `get_class`.
$className = get_class($foo);
$className::bar();

// Instead of the above, I can just do `$foo::bar();`
}

callbar(new SubFoo); // => "hi subfoo"

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