PHP abstract properties

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

    PHP 7 makes it quite a bit easier for making abstract "properties". Just as above, you will make them by creating abstract functions, but with PHP 7 you can define the return type for that function, which makes things a lot easier when you're building a base class that anyone can extend.

    FooProp();
      }
    
      public function bar() {
        return $this->BarProp()->name();
      }
    
    }
    
    class BarClass {
    
      public function name() {
        return 'Bar!';
      }
    
    }
    
    class FooClass extends FooBase {
    
      public function FooProp(): string {
        return 'Foo!';
      }
    
      public function BarProp(): BarClass {
        // This would not work:
        // return 'not working';
        // But this will!
        return new BarClass();
      }
    
    }
    
    $test = new FooClass();
    echo $test->foo() . PHP_EOL;
    echo $test->bar() . PHP_EOL;
    

提交回复
热议问题