PHP abstract properties

前端 未结 9 1423
终归单人心
终归单人心 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:46

    No, there is no way to enforce that with the compiler, you'd have to use run-time checks (say, in the constructor) for the $tablename variable, e.g.:

    class Foo_Abstract {
      public final function __construct(/*whatever*/) {
        if(!isset($this->tablename))
          throw new LogicException(get_class($this) . ' must have a $tablename');
      }
    }
    

    To enforce this for all derived classes of Foo_Abstract you would have to make Foo_Abstract's constructor final, preventing overriding.

    You could declare an abstract getter instead:

    abstract class Foo_Abstract {
      abstract public function get_tablename();
    }
    
    class Foo extends Foo_Abstract {
      protected $tablename = 'tablename';
      public function get_tablename() {
        return $this->tablename;
      }
    }
    

提交回复
热议问题