Why can't I print anything using __toString () in PHP?
I created a class with a constructor and a toString method, but it doesn't work.
class Course
{
protected $course
public function __construct()
{
$this->$course = "hello";
}
public function __toString()
{
$string = (string) $this->$course;
return $string;
}
}
I am getting the error:
Fatal error: Cannot access empty property
if i just do:
$string = (string) $course;
Nothing prints.
I am new to magic methods in PHP, although I am familiar with Java's toString method.
source to share
there is a little typo in your constructor, it should be:
protected $course;
public function __construct()
{
$this->course = "hello"; // I added $this->
}
if you now call your function __toString()
, it will print "hello".
Update
You must change the function __toString()
as follows:
public function __toString()
{
return $this->course;
}
Your generic code will become: (go copy paste :))
class Course
{
protected $course;
public function __construct()
{
$this->course = "hello";
}
public function __toString()
{
return $this->course;
}
}
source to share
You understood the magic method, but you have an error: $ course is not defined.
Your error is on this line:
$string = (string) $this-> $course;
It should be
$string = (string) $this->course;
You may know that in PHP you can do something like this:
$course='arandomproperty';
$string = $this->$course; //that equals to $this->arandomproperty
Here $ course is undefined, so it defaults to '' (and throws a NOTICE error, which you should display or log at least during development)
Edit:
You also have an eror in the constructor, you should do$this->course='hello';
change 2
Here is the working code. Is there something you don't understand here?
<?php
class Course
{
protected $course;
public function __construct()
{
$this->course = "hello";
}
public function __toString()
{
$string = (string) $this->course;
return $string;
}
}
$course = new Course();
echo $course;
source to share