简体   繁体   中英

php abstract class property from another abstract class

I'm learning oriented object PHP and I think that I'm doing something stupid.

I have an abstract userManager class, and I want to assign it a $db property that will be the instance of my abstract database class.

The database class is :

abstract class Bdd{         
        private static $instance = null;

        public static function getInstance() {
            return self::$instance;
        }

And the userManager class is :

abstract class usersManager{
        public $db = Bdd::getInstance();

I have an error on this line : public $db = Bdd::getInstance();

(Parse error: syntax error, unexpected '(', expecting ',' or ';')

Is this wrong ?

I think that I misunderstood the abstract classes, is a singleton better in my case ?

You cant call a method when you are declaring a class variable, you will need to do

public $db = null
public function __construct() {
  $this->db = Bdd::getInstance();
}

The only gotcha with this is when you extend this class and you need to create a constructor you will need to call this constructor as well by doing parent::__construct();

public $db = Bdd::getInstance(); 

Error occurs due to above line. You can't call a method when declaring variable.

Class parameters must be able to be evaluated at compile-time, NOT run-time. Basically you can only predefine simple values such as strings, null, int's ect

Because the result of Bdd:getInstance() cannot be known until it is run (ie run time), it cannot be used as a predefined value.

You should instead set the parameter to null, then set up the DB instance in your classes constructor method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM