I’ve created a class with a constructor and a toString method but it’s not working.
class Course
{
protected $course
public function __construct()
{
$this->$course = "hello";
}
public function __toString()
{
$string = (string) $this->$course;
return $string;
}
}
I get the error:
Fatal error: Cannot access empty property
if I just do:
$string = (string) $course;
Nothing prints out.
I’m new to magic methods in PHP though I’m familiar with Java’s toString method.
there is a little typo in your constructor, it should be:
if you now call your
__toString()function it will print “hello”.Update
You should change the
__toString()function like this:Your total code would become this: (go copy paste 🙂 )