繁体   English   中英

php - 如何通过construct()从另一个函数访问返回值?

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

我试图访问__constructor() test()的返回值,但我坚持了下来。 任何人都可以告诉我如何从__constructor()获取返回值。 我很感激你的回答!

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

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

$some = new some;


echo $some;

print_r($some);

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

谢谢!

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

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();

简单的方法是在你的类中实现__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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM