PHP OOP - 如何调用main函数和子函数

时间:2014-02-11 09:08:09

标签: php

我必须学习OOP链接:

$data = new myclass;
$data->sub_function()->main_function();

但现在我想编码它看起来像这样:

$data = new myclass;
$main = $data->main_function();
$sub = $main->sub_function();

如果是这样,如何为此编写类函数?

请帮助我!

2 个答案:

答案 0 :(得分:5)

class myclass {

    public function main_function() {
        //Do your actions here
        return $this;
    }

    public function sub_function() {
        //Do your actions here
        return $this;
    }
}

答案 1 :(得分:0)

class myclass {
    public function main_function() {
        return 'MAIN ';
    }
    public function sub_function($str) {
        if ($str == 1) $result = 'SELECT 1';
        else if ($str == 2) $result = 'SELECT 2';
        else $result = 'NOT FOUND';
        return $result;
    }
}
$data = new myclass;
$main = $data->main_function();
$sub = $main->sub_function(1);
echo $sub; // Fatal error: Call to a member function sub_function() on a non-object...

我需要在每个函数中返回字符串(不是设置值/键)