parent :: method does not return connection

0

I have a Conn class that makes a connection to a SQL Server:

class Conn
{
    protected $con;
    protected $a = 'aaa';

    function __construct()
    {
        $this -> conecta();
    }

    private function conecta(){
        $serverName = "xxx.xxx.xxx.xxx";
        $connectionInfo = array( "Database"=>"XXX", "UID"=>"YYY", "PWD"=>"ZZZ", "CharacterSet" => "UTF-8");

        try {
            $conn = sqlsrv_connect($serverName, $connectionInfo);
        } catch (Exception $e) {
            echo "Erro na conexão com o BD.<br/>";
            die( print_r(sqlsrv_errors(), true));
        }

        if (!$conn){
            echo "Erro na conexão com o BD.<br/>";
            die( print_r(sqlsrv_errors(), true));
        } else {
            $this -> con = $conn;
            var_dump($this -> con);
        }
    }

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

}

And a BD class that extends the Conn class:

class BD extends Conn
{
    private $cnx;

    function __construct()
    {
        $this -> cnx = parent::getCon();
        var_dump($this -> cnx);
    }
}

When I create a BD object:

If in method getCon() I set return $this -> a; , it returns me: string(3) "aaa"

If in method getCon() I set return $this -> con; , it returns me: NULL where it should return resource(3) of type (SQL Server Connection)

I'd like to know what might be causing this or if I'm using it incorrectly.

    
asked by anonymous 20.07.2018 / 14:42

1 answer

1

The $con object in Conn is only initialized when the Conn::conecta method is called, which in turn is called in the Conn constructor, but the Conn constructor is never called because the method was overridden in the child class BD .

If you need to override the constructor, you need to explicitly call the constructor of the parent class:

class BD
{
    public function __construct()
    {
        parent::__construct();
        // ...
    }
}

So, the constructor of the parent class will be executed, calling the conecta method and initializing the $con object. This way you can do:

class BD
{
    public function __construct()
    {
        parent::__construct();
        $this->cnx = $this->getCon();
    }
}

Note that it was invoked as $this->getCon() , since, as the Conn::getCon method is protected , it will inherit in BD as private , accessible within the class.

    
20.07.2018 / 14:57