Take the 2-minute tour ×

Why does PHP think I want to convert that object to a string?

class Class1 {}

class Class2 {
    function __construct( Class1 $class1Obj) {
        $this->$class1Obj = $class1Obj; // -> Catchable fatal error: Object of class Class1 could not be converted to string

$class1Obj = new Class1();
$class2Obj = new Class2($class1Obj);
share|improve this question
add comment

3 Answers

up vote 5 down vote accepted

Is it an extra $? That would be better:

$this->class1Obj = $class1Obj;
share|improve this answer
How embarrassing. A bit tired maybe. Can´t delete the question. –  Laurent CAPRANI Jul 3 '13 at 20:38
add comment

$this->$class1Obj try's to create a public string property with Class2 as property name.

That's why you get a fatal error try this code for Class1

class Class1 {
   public function __toString() {
      return 'Class1'; 

Edit: To late with answer

share|improve this answer
add comment

To explain a bit more, when you do this :

$this->$class1Obj = $class1Obj;

What you are actually trying to do is assign the value of $class1Obj in $this->[valueOf$class1Obj]. Let's do an example, let's say $class1Obj has this value :

$class1Obj = "test123";

Doing this following line :

$this->$class1Obj = $class1Obj;

Would be the equivalent of doing this :

$this->test123 = "test123";
share|improve this answer
You are right. The said conversion is not the assignment but the left hand side: $this->$class1Obj is first converted to $this->[stringValueOfClass1Obj]. –  Laurent CAPRANI Jul 4 '13 at 2:15
add comment

Your Answer


