I have a class address_book in which I want to set $DBConnection using method from another class:
JavaScript
x
<?php
class address_book
{
protected $DBConnection;
public function __construct()
{
$this->DBConnection=new address_book_db();
$this->init();
}
public function init()
{
add_shortcode('address_book', array($this,'load'));
}
public function load()
{
var_dump($DBConnection);
}
}
Another class:
JavaScript
<?php
class address_book_db
{
protected $dbconnection;
public function __construct()
{
$this->dbconnection='1';
}
}
So var_dum should return ‘1’ as it has to be assigned to protected $DBConnection; in the first class. I’m starting my learning of PHP OOP so probably everything is bad.
Any way it has to work like this. In first class I load db name which is being loaded from another class using methods which determines db name (not developed yet because I just want to pass this constructed dbname to first class).
Advertisement
Answer
You’re missing $this->
to refer to the class property.
The property’s value contains another class, so you have to refer to that class its property as wel with a second ->
var_dump($this->DBConnection->dbconnection)