请看下面的示例代码。由此,我得到了索引、test_1和test_2函数。
如果执行索引函数的case-1语句,我会得到输出12。但是case-2语句会得到错误消息: Call to a member function test_2() on null。
有没有人能帮我使case-2语句起作用?
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Debug extends CI_Controller
{
public function index()
{
//case 1 : Working
$this->test_1();
$this->test_2();
//case 2: Not Working
echo $this->test_1()->test_2();
}
function test_1()
{
echo "1";
}
function test_2()
{
echo "2";
}
} ?>提前谢谢..
发布于 2020-01-05 02:22:31
为了实现$this->test1()->test2()调用,需要在每个函数中返回$this。
更新代码:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Debug extends CI_Controller
{
public function index()
{
//case 1 : Working
$this->test_1();
$this->test_2();
//case 2: Working
echo $this->test_1()->test_2();
}
function test_1()
{
echo "1";
return $this;
}
function test_2()
{
echo "2";
return $this;
}
} ?>https://stackoverflow.com/questions/59592388
复制相似问题