Johnathan Au
Johnathan Au

Reputation: 5362

Why can't I print anything with __toString() in PHP?

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.

Upvotes: 3

Views: 606

Answers (2)

haltabush
haltabush

Reputation: 4528

You've understood the magic method all right, but you have an error here : $course is not defined.

Your error is on this line:

    $string = (string) $this-> $course;

It should be

    $string = (string) $this->course;

You might know that in PHP you can do something like this:

$course='arandomproperty';
$string = $this->$course; //that equals to $this->arandomproperty

Here, $course is not defined, so it defaults to '' (and throw a NOTICE error, which you should display or log at least during development)


Edit:
You also have an eror in you constructor, you should do $this->course='hello';


edit 2

Here is a working code. Is there is 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;

Upvotes: 7

Bazzz
Bazzz

Reputation: 26912

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 __toString() function it will print "hello".

Update
You should change the __toString() function like this:

public function __toString()
{
    return $this->course;
}

Your total code would become this: (go copy paste :) )

class Course
{
    protected $course;
    public function __construct()
    {
        $this->course = "hello";
    }

    public function __toString()
    {
        return $this->course;
    }
}

Upvotes: 9

Related Questions