访问类方法

时间:2013-01-05 23:09:16

标签: php

我的课程:

class mvc {
    public function home () {
        return 'index';
    }
}

对象:

include "./sys/controller/".$Current_page_Controller_name.".php";

        // making object of the controller class.
            $controller = new $Current_page_Controller_name;

        // Cheks if model is called, m stands for "model"
            if (isset($_GET['m'])) {

            }

            $method_name = $mvc->$Current_page_Controller_name.'()';

    // Cheks if default model exists, if not gives an error.
        if (method_exists($controller, $method_name)) {
            echo "+";
        } else {
            echo "-";
            //die("Lappas sledzis saplisis, gaidiet drizuma... (2)");
        }

我一直在犯这个错误

Notice: Undefined property: mvc::$home in /home/unusuallv/domains/.../public_html/sys/config.php on line 51

问题接近$ method_name = $ mvc-> $ Current_page_Controller_name。'()';我知道,但我无法弄明白:// tnx很多!

3 个答案:

答案 0 :(得分:0)

您正在调用该函数,这就是错误。你不想打电话,但得到它的名字。为此,您无需$method_name = $mvc->$Current_page_Controller_name.'()';,而是$method_name=Current_page_Controller_name;,然后将其称为:$mvc->$method_name()

当PHP处理您的脚本时,它会在您从$mvc->$Current_page_Controller_name.'()'访问变量时考虑$mvc,然后将其附加到字符串'()'

考虑以下这些例子:

//somewhere file
class MVC{
public $someVar="QWERTY";
public function abc(){/*...*/}
public function parseResponse(){/*...*/}
};
///.....
$mvc=new MVC;
$abc="someVar";
$x=$mvc->$abc."()";
echo $x;//gives you "QWERTY()"

$b=method_exists($mvc,$abc);//false
$b=method_exists($mvc,'abc');//true
//call function
$abc="parseResponse";
$mvc->$abc();//calls MVC::parseResponse

答案 1 :(得分:0)

$method_name = $mvc->$Current_page_Controller_name.'()';

应该是这样的:

$method_name = $mvc->$Current_page_Controller_name();

答案 2 :(得分:0)

在以下表达式中:


$method_name = $mvc->$Current_page_Controller_name.'()';

->运算符的优先级高于字符串连接运算符(.)。这意味着PHP首先计算表达式$mvc->$Current_page_Controller_name,因此它尝试访问mvc类的home属性(不存在)。

请改用:


$method_name = $mvc->$Current_page_Controller_name();