Can't figure out $this pseudo-variable in the current code

oop

#1

I have struggle to figure out this piece of code:

class Commons {

	public $dbh = null;

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

I can’t understand this part after equally sign: $db->dbh;
Okay, I accessed to $dbh property but what it really means?

Thank you for your time


#2

That code doesn’t make any sense. It should have probably been:

class Commons {

	public $dbh = null;

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

Also Commons is a very very generic name. If you can’t name a concept properly you don’t understand it well enough.


#3

Thank you for reply
This is code I found on phpocean.com, it’s basically crud system, I am just trying to break it down, learn, and you are completely right about $this->dbh = $db;, that’s why I cant understand it…


#4

As it stands in the code you posted it just sets $this->dbh to null again. So basically the code would be the same if you remove that line. It works, but it’s not doing anything useful.

Sounds like you should be careful about what you read on that site if they make these kinds of blatant mistakes.


#5

If you type-hint the parameters, it’s much harder to instantiate with the wrong variables.

class Commons 
{
	protected $dbh;

	public function __construct(PDO $db) {
		$this->dbh = $db;
	}
}

This way you can only pass PDO instances (before that you could pass anything, e.g. letters) and this now guarantees that $this->dbh will be a database connection.

I’ve also changed the property to be non-public, otherwise it could be changed at will making the property invalid again.