RD Ward
RD Ward

Reputation: 6737

Defining a property based on a parent's method in PHP

class UserInfo extends Database{

    private $privileges=
        $this
            ->connect()
            ->select("users", "DISTINCT privileges", "username= 'someuser'")
            ->getResult('privileges');

}

It doesn't seem like it is possible for me to be able to define this property $privileges based on a method based on the parent class Database.

It is worth pointing out the same function works splendidly when I use the same function in a different script and define the properties dynamically. Each class is instantiated by an object, it works (obviously with the proper setters and getters.)

$db = new Database;
$user = new UserInfo;
$user-> privileges= 
    $db
        ->connect()
        ->select("users", "DISTINCT privileges", "username= '".$user->name."'")
        -> getResult('privileges');

Upvotes: 0

Views: 48

Answers (2)

Alessandro Desantis
Alessandro Desantis

Reputation: 14343

You can't put an expression when defining a property's value inside a class. Use the constructor for that:

<?php
class UserInfo extends Database
{
    // ...

    public function __construct()
    {
        // initialize the 'privileges' property
    }
}
?>

Upvotes: 2

Yogu
Yogu

Reputation: 9445

The new instance (this) is not ready when the private members are initialized. You have to put that code into the constructor.

Upvotes: 0

Related Questions