What is __get()

class Penguin extends Animal {

	public function __construct($id) {
		$this->getPenguinFromDb($id);
	}

	public function getPenguinFromDb($id) {
	// elegant and robust database code goes here
	}
}

Now if our penguin has the properties “name” and “age” after it is loaded, we’d be able to do:

$tux = new Penguin(3);
echo $tux->name . " is " . $tux->age . " years old\n";

However imagine something changed about the backend database or information provider, so instead of “name”, the property was called “username”. And imagine this is a complex application which refers to the “name” property in too many places for us to change. We can use the __get method to pretend that the “name” property still exists:

class Penguin extends Animal {

	public function __construct($id) {
		$this->getPenguinFromDb($id);
	}

	public function getPenguinFromDb($id) {
	// elegant and robust database code goes here
	}

	public function __get($field) {
		if($field == 'name') {
			return $this->username;
	}
}

 

This technique isn’t really a good way to write whole systems, because it makes code hard to debug, but it is a very valuable tool. It can also be used to only load properties on demand or show calculated fields as properties, and a hundred other applications that I haven’t even thought of!

Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
Yes0
No0
Harinder Singh

Harinder Singh

My name is Harinder Singh and I specialize in Software industry. I consider myself as a life learner. I love learning new concepts, embracing new ideas and reading and searching for innovation.