PHP abstract properties

前端 未结 9 1422
终归单人心
终归单人心 2020-12-07 16:16

Is there any way to define abstract class properties in PHP?

abstract class Foo_Abstract {
    abstract public $tablename;
}

class Foo extends Foo_Abstract          


        
9条回答
  •  萌比男神i
    2020-12-07 16:57

    I've asked myself the same question today, and I'd like to add my two cents.

    The reason we would like abstract properties is to make sure that subclasses define them and throw exceptions when they don't. In my specific case, I needed something that could work with statically.

    Ideally I would like something like this:

    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.
    }
    

    I ended up with this implementation

    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
    {
    }
    

    As you can see, in A I don't define $prop, but I use it in a static getter. Therefore, the following code works

    B::getProp();
    // => 'B prop'
    
    $b = new B();
    $b->getProp();
    // => 'B prop'
    

    In C, on the other hand, I don't define $prop, so I get exceptions:

    C::getProp();
    // => Exception!
    
    $c = new C();
    $c->getProp();
    // => Exception!
    

    I must call the getProp() method to get the exception and I can't get it on class loading, but it is quite close to the desired behavior, at least in my case.

    I define getProp() as final to avoid that some smart guy (aka myself in 6 months) is tempted to do

    class D extends A {
        public static function getProp() {
            // really smart
        }
    }
    
    D::getProp();
    // => no exception...
    

提交回复
热议问题