Problems instantiating the object

0
public function select($sql, $array = array())
{
    $sth = $this->conn->prepare($sql);
    if(!empty($array)){
        foreach ($array as $key => $value) {
            $sth->bindValue(":".$key, $value);
        }
    }
    $this->stmt = $sth;
}

public function execute(){
    if($this->stmt->execute()){
        return $this->stmt;
    } else {
        return false;
    }
}


$database = new DataBase();

//1º : Assim não funciona:
$database->select(
    "SELECT * FROM tabela WHERE id=:id",
    array("id" => 1)
)->execute();

//2º : Assim funciona:
//$stmt = $database->execute();

You're experiencing this error: Fatal error: Call a member function execute () on a non-object in

Does anyone know why the first mode does not work?

    
asked by anonymous 16.05.2016 / 04:57

1 answer

1

To use method chaining , the select method needs to return the instance itself. It would be enough to use return $this in threaded methods.

public function select($sql, $array = array())
{
    ...
    return $this;
}


$database = new DataBase();

$database-> select( "SELECT * FROM tabela WHERE id=:id" , array("id" => 1) )
         -> execute();

The second form you presented works because there is no concatenation of methods.

$database = new DataBase();

$database-> select( "SELECT * FROM tabela WHERE id=:id" , array("id" => 1) );
$database-> execute();
    
16.05.2016 / 08:09