Class constructor interfering with another class

Essentially, I just create two classes where one class, in this case class A, runs a function in another class, in this case class B, to capture some information from the database.

However, when it B_runtime()really calls the database, I get an error Cannot access protected property A::$db.

I do not understand that although I have two __constructin both classes, the PDO statement is very stable when using a database connection from class A.

I am sure that this is due to the fact that I am starting B_runtime()from class A, because this does not happen if I call it from outside of class A.

I know that I can simply change protected $db;in class A to a public variable, however I am really interested to know how I can fix this.

ob_start();
include('/config.php');
ob_end_clean();

$A = new A($db);
$B = new B($db);

echo $A->A_runtime();

class A{
    protected $db;
    public function __construct($db){
       $this->db = $db;
    }
    public function A_runtime(){
        return B::B_runtime();      
    }
}

class B{
    protected $db;
    public function __construct($db){
       $this->db = $db;
    }
    public function B_runtime(){
        $preparedStatement = $this->db->prepare('SELECT * FROM z_mod_html WHERE ModuleLink = :moduleid LIMIT 1');
        $preparedStatement->execute(array(':moduleid' => '1'));
        $rows = $preparedStatement->fetchAll();
        return $rows[0]['HTML'];
    }
}

Sorry for the long code - if anyone has any ideas or suggestions, we will be very grateful. Thank.

+5
source share
2 answers

You can pass instance B to a method. Thus, you also determine the dependence of your method on class B.

$A = new A($db);
$B = new B($db);

echo $A->A_runtime($B);

class A{
    //...
    public function A_runtime($instance){
        return $instance -> B_runtime();      
    }
}

You can even use the hinting type in PHP 5 to signal that you are expecting an instance of class B there:

    public function A_runtime(B $instance){
+3

Oy.

firstly, you call a non-static method as a static method.

B::B_runtime();

should be used only this way if B_runtime is declared as a static method

static public function B_runtime(){

-, , . , , . . somthing, , , , , .

public function A_runtime(B $object_b){

, hinting . B B, - .

interface BInterface {
   public function B_runtime();
}

public function A_runtime(BInterface $object_b){

SOLID OO.

http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)

+3

All Articles