silentw
silentw

Reputation: 4885

Object could not be converted to string

The global variable is a class (object) already defined earlier

class Users
{
    private $sql;

    public function __construct() {
        global $sql;
        $this->$sql = $sql;
    }
}

I'm trying to assign the object to a private variable in my other class (Users) so I don't have to use this line global $sql; through all the functions in Users but it's giving me this error:

Catchable fatal error: Object of class Bdcon could not be converted to string in /home/<<NAME>>/public_html/<<NAME>>/classes/class.users.php on line 8

Upvotes: 0

Views: 168

Answers (3)

AmazingDreams
AmazingDreams

Reputation: 3204

You don't access the private $sql in the right way. It should be:

$this->sql = $sql;

The reason you get the error is that if you use $this->$sql, $sql is cast to a string and php tries to look for a property with the name of the value of $sql.

Upvotes: 1

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146410

You can't (normally) use an object as property name:

$this->$sql
       ^

But you don't really want:

$this->sql

Whatever, I recommend this other style:

class Users
{
    private $sql;

    public function __construct(Bdcon $sql) {
        $this->sql = $sql;
    }
}

Upvotes: 1

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

Use $this->sql. because you are accessing property of the class so no need to add $ sign instead use $this->

Upvotes: 0

Related Questions