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

时间:2018-10-08 10:34:46

标签: php oop

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

我想知道这是否被认为是不好的做法?

或者该功能是否会在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"

1 个答案:

答案 0 :(得分:3)

作为一般规则,使用静态方法是不好的做法,因为:

  1. 实际上,静态方法或静态变量是全局变量
  2. 使用静态代码制作可能会导致很多测试麻烦
  3. 静态代码使部分代码之间具有很高的内聚力
  4. 静态代码在代码的各个部分之间隐藏了依赖关系

但是,在某些情况下使用静态代码是合理的。例如:

  1. 方法引用类而不引用对象
  2. 没有状态的助手或Util类