FLX
FLX

Reputation: 2679

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 ?

Upvotes: 0

Views: 140

Answers (3)

Kris
Kris

Reputation: 6122

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();

Upvotes: 3

Lee
Lee

Reputation: 10603

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 e.c.t.

Because the result of Bdd:getInstance() cannot be known until it is run (i.e. 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.

Upvotes: 0

som
som

Reputation: 4656

public $db = Bdd::getInstance(); 

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

Upvotes: 0

Related Questions