将GET变量传递给PHP以实例化类和调用函数

时间:2012-04-09 20:36:23

标签: php html function variables get

我成功实例化了对象类,但我无法弄清楚如何调用函数。 这是我的PHP代码:

$obj = new router();
class router{

public function __construct(){
    if($_SERVER['REQUEST_METHOD'] == 'GET'){
        echo "GET";
        $page = 'index';
        $funct = 'myfuncempty';

        if (!empty ($_GET)){
            $page = $_GET['page'];
            $funct = $_GET['func'];
        }
        $obj = new $page(); //instantiating object with get from class
        $obj->funct;
    }
    else{
        echo "POST";
    }

}

}
class index{

public function __construct(){
    echo "hello I'm index";
}
public function myfunc(){
    echo "yo";
}

public function myfuncempty(){
    echo "empty get";
}
}

class login{
public function __construct(){
    echo "hello I'm login";
}

public function loggedin(){
    echo "you're logged in";
}

public function loggedinempty(){
    echo "its empty";
}
}

这是我用来通过GET传递变量的HTML表单:

<html>
<head></head>
<body>
<form action="index.php" method="POST"><input type ="text" name="page" id="page" /><input type="submit" /></form>
<form action="index.php" method="GET">Page:<input type="text" name="page" id="page" />Function:<input type="text" name="func" id="func" /><input type= "submit" />
</body>
</html>

当我输入page for page和myfunc in for function时,我收到了这个回复:

GEThello I'm login Notice: Undefined property: login::$funct in /home/cr47/public_html/final_project/index.php on line 27

因此,它正确地传递'page'并实例化对象,但它没有正确调用myfunc函数。 有什么想法吗?

1 个答案:

答案 0 :(得分:2)

$obj->funct;替换为$obj->$funct();

要小心。你不应该让你的用户实例化任意类。至少使用白名单或要求它们是某些自定义类的子类,这些类仅由您的类使用,这些类是安全的(即没有公共方法可以做任何用户不能做的事情)。