PHP abstract properties

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

    The need for abstract properties can indicate design problems. While many of answers implement kind of Template method pattern and it works, it always looks kind of strange.

    Let's take a look at the original example:

    abstract class Foo_Abstract {
        abstract public $tablename;
    }
    
    class Foo extends Foo_Abstract {
        //Foo must 'implement' $property
        public $tablename = 'users';   
    }
    

    To mark something abstract is to indicate it a must-have thing. Well, a must-have value (in this case) is a required dependency, so it should be passed to the constructor during instantiation:

    class Table
    {
        private $name;
    
        public function __construct(string $name)
        {
            $this->name = $name;
        }
    
        public function name(): string
        {
            return $this->name;
        }
    }
    

    Then if you actually want a more concrete named class you can inherit like so:

    final class UsersTable extends Table
    {
        public function __construct()
        {
            parent::__construct('users');
        }
    }
    

    This can be useful if you use DI container and have to pass different tables for different objects.

提交回复
热议问题