如何通过 PHP 中另一个函数的 construct() 访问 Return 值?

How can i access Return value throught the construct() from another function In PHP?

我正在尝试访问 __constructor()test() 的 return 值,但我卡住了。任何人都可以告诉我如何从 __constructor() 中获取 return 值。感谢您的回答!

class some
{
    public function __construct()
    {
        $this->test(); // I want this test()
    }

    public function test() 
    {
        return 'abc';
    }
}

$some = new some;


echo $some;

print_r($some);

我自己试过,没有任何反应!

谢谢!

构造函数没有 return 值,你不能只回显一个对象,试试这个。

class some
{
    private $my_string;

    public function __construct()
    {
        $this->my_string = 'abc';
    }

    public function test() 
    {
        return $this->my_string;
    }
}

$some = new some;


echo $some->test();

简单的方法是在 class

中实现 __toString()
public function __toString()
{
    return $this->test();
}

打印您的对象

echo $some; // 'abc'


您可以改进您的代码:

class Some
{
    protected $test;

    public function __construct($value)
    {
        $this->test = $value;
    }

    public function __toString()
{
    return 'Your Value: ' . $this->test;
}
}

$some = new Some('Hello World');

echo $some; // Your Value: Hello World