开发者

Call a function based on variable in parent controller [duplicate]

This question already has answers here: Call to a member function on a non-object [duplicate] (8 answers) Closed 9 years ago.

I'm writing a micro MVC framework, and I want to be able to run a function based on the action in the URL given. I currently do:

function action($id, $function){

${$id}->{$function}();

}

Where the $id is the model/view/controller to load, and the $function is the action. This apparently works, but not in the MainController. I'd have to put it in the startup script which would be limiting as I want people to be able to run action from inside the view so that they can perform different actions based on what they give the function.

Fatal error: Call to a member function testFunction() on a non-object in /home/cherwell/public_html/scott/develop/simple/system/controllers/MainController.php on line 20

Anyone know a way around it so that I can call a function from the child controller from the MainController?

Cheers!

EDIT: I have made the action work by doing:

if($action != false){

${$id}开发者_StackOverflow->{$action}();

} else {

include("system/views/".$id.".php");
}

$id and $action are always defined, so it works fine. The only problem I have now is that any functions must have all of the globals (its a long list):

global $id; 
global ${$id};
global $site;
global $start;
global $action;
global $param;
global $helper;
global $model;

if they need any of these (which, they do if you need to call methods from the maincontroller/helper/model)...

I don't know why variables aren't being passed down into the functions. I have declared the class for the respective ID too...

EDIT 2: Example.

function testFunction(){
global $helper;
$helper->test();

$this->render("home");

}

Works, but when I remove the global $helper; it fails. Even if I have a load of globals in the startup, construct of child and parent, it still fails. This also happens for every function (needing globals). Can anyone help?


have you tried use a function dedicated to prevent this sort of coding?

function action($id, $function, $params = array())
{
    if(!is_object($id))
    {
        $id = new $id; //Or just use globalization or something to bring it in scope.
    }

    call_user_func_array(array($id,$function),$params);
}


In this case ${$id} is null because it haven't been set. Are you trying to do something like the following?

function action($id, $function){

   $controller = new $id();
   $controller->{$function}();

}


How about:

$app = new myApp();
function action ($action)
{
    global $app;
    if (!method_exists($app,$action)) return;
    $app->$action();
}


I ended up making an __init() function in the main controller that was called upon on loading of the site. Works nicely. Now models/helpers/view and controller work perfectly.

Thanks for the help though! :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜