【问题标题】:How can i access Return value throught the construct() from another function In PHP?如何通过 PHP 中另一个函数的构造()访问返回值?
【发布时间】:2018-08-20 01:13:26
【问题描述】:
我试图访问__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);
我自己试过了,但没有任何反应!
谢谢!
【问题讨论】:
标签:
javascript
php
mysql
php-7
php-7.2
【解决方案1】:
构造函数不返回值,你不能只回显一个对象,试试这个吧。
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();
【解决方案2】:
简单的方法是在你的类中实现__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