gpt4 book ai didi

php - 为什么我不能在 PHP 中使用 __toString() 打印任何内容?

转载 作者:可可西里 更新时间:2023-10-31 23:55:03 25 4
gpt4 key购买 nike

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

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

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

我得到错误:

Fatal error: Cannot access empty property 

如果我这样做:

$string = (string) $course;

没有打印出来。

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

最佳答案

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

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

如果您现在调用 __toString() 函数,它将打印“hello”。

更新
您应该像这样更改 __toString() 函数:

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

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

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

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

关于php - 为什么我不能在 PHP 中使用 __toString() 打印任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9915335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com