有没有办法在PHP中定义抽象类属性?
abstract class Foo_Abstract {
    abstract public $tablename;
}
class Foo extends Foo_Abstract {
    //Foo must 'implement' $property
    public $tablename = 'users';   
}发布于 2016-07-15 21:48:16
今天我问了自己同样的问题,我想补充我的两点意见。
我们喜欢abstract属性的原因是确保子类定义它们并在子类不定义时抛出异常,在我的特定情况下,我需要一些可以与statically一起工作的东西。
理想情况下,我喜欢这样的东西:
abstract class A {
    abstract protected static $prop;
}
class B extends A {
    protected static $prop = 'B prop'; // $prop defined, B loads successfully
}
class C extends A {
    // throws an exception when loading C for the first time because $prop
    // is not defined.
}我最终得到了这个实现。
abstract class A
{
    // no $prop definition in A!
    public static final function getProp()
    {
        return static::$prop;
    }
}
class B extends A
{
    protected static $prop = 'B prop';
}
class C extends A
{
}正如您所看到的,在A中,我没有定义$prop,但我在static getter中使用它。因此,下面的代码可以正常工作
B::getProp();
// => 'B prop'
$b = new B();
$b->getProp();
// => 'B prop'另一方面,在C中,我没有定义$prop,所以我得到了异常:
C::getProp();
// => Exception!
$c = new C();
$c->getProp();
// => Exception!我必须调用getProp()方法来获取异常,但我无法在类加载时获取它,但它非常接近所需的行为,至少在我的例子中是这样。
我将getProp()定义为final是为了避免某些聪明人(6个月后我自己)想要做的事情
class D extends A {
    public static function getProp() {
        // really smart
    }
}
D::getProp();
// => no exception...https://stackoverflow.com/questions/7634970
复制相似问题