为什么我不能用PHP中的__toString()打印任何东西?

Joh*_* Au 3 php tostring magic-methods

我创建了一个带有构造函数和toString方法的类,但它不起作用.

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

    public function __toString()
    {
        $string = (string) $this->$course;
        return $string;
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到错误:

Fatal error: Cannot access empty property 
Run Code Online (Sandbox Code Playgroud)

如果我这样做:

$string = (string) $course;
Run Code Online (Sandbox Code Playgroud)

什么都没打印出来.

虽然我熟悉Java的toString方法,但我不熟悉PHP中的魔术方法.

Baz*_*zzz 9

你的构造函数中有一个小错字,它应该是:

protected $course;
public function __construct()
{
    $this->course = "hello"; // I added $this->
}
Run Code Online (Sandbox Code Playgroud)

如果您现在调用您的__toString()函数,它将打印"hello".

更新
你应该改变这样的__toString()功能:

public function __toString()
{
    return $this->course;
}
Run Code Online (Sandbox Code Playgroud)

你的总代码将成为这个:(去复制粘贴:))

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

    public function __toString()
    {
        return $this->course;
    }
}
Run Code Online (Sandbox Code Playgroud)


hal*_*ush 7

你已经理解了魔术方法,但你在这里有一个错误:$ course未定义.

你的错误是在这一行:

    $string = (string) $this-> $course;
Run Code Online (Sandbox Code Playgroud)

它应该是

    $string = (string) $this->course;
Run Code Online (Sandbox Code Playgroud)

您可能知道在PHP中可以执行以下操作:

$course='arandomproperty';
$string = $this->$course; //that equals to $this->arandomproperty
Run Code Online (Sandbox Code Playgroud)

这里,$ course没有定义,所以它默认为''(并抛出一个NOTICE错误,你应该在开发过程中显示或记录)


编辑:
你在构造函数中也有一个错误,你应该这样做$this->course='hello';


编辑2

这是一个有效的代码.你有什么不明白的地方吗?

<?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;
Run Code Online (Sandbox Code Playgroud)