PHP abstract properties

前端 未结 9 1440
终归单人心
终归单人心 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条回答
  •  生来不讨喜
    2020-12-07 17:01

    As stated above, there is no such exact definition. I, however, use this simple workaround to force the child class to define the "abstract" property:

    abstract class Father 
    {
      public $name;
      abstract protected function setName(); // now every child class must declare this 
                                          // function and thus declare the property
    
      public function __construct() 
      {
        $this->setName();
      }
    }
    
    class Son extends Father
    {
      protected function setName()
      {
        $this->name = "son";
      }
    
      function __construct(){
        parent::__construct();
      }
    }
    

提交回复
热议问题