我发现在某些用例中通过对象调用静态方法非常方便。
我想知道这是否被认为是一种糟糕的做法?
还是在将来的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"发布于 2018-10-08 10:56:06
一般来说,使用静态方法是错误的做法,因为:
但是,在某些情况下,使用静态代码是合理的。例如:
https://stackoverflow.com/questions/52700402
复制相似问题