Problems when instantiating the object

Asked

Viewed 27 times

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 are showing this error: Fatal error: Call to a Member Function execute() on a non-object in

Does anyone know why the first mode does not work?

1 answer

1

To use chaining of methods, the method select need to return the instance itself. Just use return $this in the chained 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 chaining of methods.

$database = new DataBase();

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.