PHP abstract properties

前端 未结 9 1406
终归单人心
终归单人心 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 16:58

    There is no such thing as defining a property.

    You can only declare properties because they are containers of data reserved in memory on initialization.

    A function on the other hand can be declared (types, name, parameters) without being defined (function body missing) and thus, can be made abstract.

    "Abstract" only indicates that something was declared but not defined and therefore before using it, you need to define it or it becomes useless.

    0 讨论(0)
  • 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();
      }
    }
    
    0 讨论(0)
  • 2020-12-07 17:02

    Depending on the context of the property if I want to force declaration of an abstract object property in a child object, I like to use a constant with the static keyword for the property in the abstract object constructor or setter/getter methods. You can optionally use final to prevent the method from being overridden in extended classes.

    Other than that the child object overrides the parent object property and methods if redefined. For example if a property is declared as protected in the parent and redefined as public in the child, the resulting property is public. However if the property is declared private in the parent it will remain private and not available to the child.

    http://www.php.net//manual/en/language.oop5.static.php

    abstract class AbstractFoo
    {
        public $bar;
    
        final public function __construct()
        {
           $this->bar = static::BAR;
        }
    }
    
    class Foo extends AbstractFoo
    {
        //const BAR = 'foobar';
    }
    
    $foo = new Foo; //Fatal Error: Undefined class constant 'BAR' (uncomment const BAR = 'foobar';)
    echo $foo->bar;
    
    0 讨论(0)
提交回复
热议问题