简体   繁体   中英

parent method retuns empty when used in a child class in php

I have a parent class ( DB ) with a public method named con() .
This method should return whatever is inside private $con - which it does both inside the class it self, and from outside.

class DB
{
    private $con = array();

    public function add($alias, $db, $un, $pw, $desc)
    {
        try {
            $options = array(/*PDO OPTIONS*/)
            $this->con[$alias] = array(
              'alias' => $alias, 
              'db' => $db, 
              'dbh' => new PDO('mysql:host=localhost;dbname='.$db.';charset=utf8', $un, $pw, $options), 'desc'=>$desc);
        } catch(PDOException $e) {
            /*  return error message  */
        }
    }

    public function con()
    {
        return $this->con;
    }
}

I'm adding connections like this:

$db = new DB();
$db->add('alias1','databasename','username','password','an optional short description');
$db->add('alias2','databasename2','username2','password2','');

Now, the private $con should be populated with two connections - which it is.
And the con() method should now return these connections - which it also does:

I put up this test function inside the KD -class:

public function aliases()
{
    foreach($this->con() as $con){    //  this should returns an array with the aliases.
        $aliases[] = $con['alias'];
    }
    return $aliases;
}

The following code returns: array(2) { [0]=> string(4) "alias1" [1]=> string(4) "alias2" }

<?=var_dump($db->aliases())?>

Now, I also created useAliases() as a test method inside a child class that extends the DB class:

class SQL extends DB
{
    public function useAliases()
    {
        var_dump($this->aliases());
    }
}

The following code returns: NULL NULL

$sql = new SQL();
var_dump($sql->useAliases());

Why does this happen? I expected that the useAliases() would return the same as aliases() .

You need to use method add() from parent class to set up your connection. Now default value of $con attribute is array() because you defined it so:

private $con = array();

so you get what is expected.

If you want it to work you need to runt it this way:

$sql = new Sql();
$sql->add('alias','db','un','pw','desc');
$sql->showTables();

EDIT

You cannot do it this way:

$db = new DB();
$db->add('alias1','databasename','username','password','an optional short description');
$db->add('alias2','databasename2','username2','password2','');
$sql = new Sql();
$sql->showTables();

because $db and $sql in this case are separate objects. You need to do it as I showed above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM