Quantcast
Channel: User andrewsi - Stack Overflow
Viewing all articles
Browse latest Browse all 51

Answer by andrewsi for Extended class instance cannot access the injected properties of the parent

$
0
0

I think you're misunderstanding how objects work.

class dog {

    public $id = 0;
    public function __construct($attributes = array()) {

        foreach($attributes as $field=>$value){
          $this->$field = $value;
        }

    }
}

class poodle extends dog {
}

When I call the construct on the dog class, I get a dog object; that is a stand-along variable, complete in itself. If I then create a poodle object, that is a new and separate object. The class is basically a blueprint to show what the object will look like when it's created - by the time you're making changes to the values of an object, you can't then change the class itself.

For what you want to do, you'll have to approach it a different way - you can't set a value in one object and then be able to access that in a different object. Instead, something like:

class DB {
    public function __construct($attributes) {
        // set up database connection here
    }
}

class User {
    public $DB;

    public function __construct ($DB) {
        $this->DB = $DB;
    }
}

$myDB = new DB();
$myUser = new User($DB);

That lets you set up a single database class, that you can pass into a second object; changes made in your database object will filter through into your Users


Viewing all articles
Browse latest Browse all 51

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>