从字符串中调用php函数名

时间:2014-02-12 22:53:47

标签: php

我创建了一个php函数来返回或保存一些jsons,这个类看起来像这样。

<?php
    class calendarModel {

        // global variables
        var $user;
        var $action;
        var $connect;

        // init class
        function __construct($action = "getEvents") {
            $this->user = 1;

            $this->action = $action;

            $dbhost = "localhost";
            $dbport = "5432";
            $dbname = "fixevents";
            $dbuser = "postgres";
            $dbpass = "123";
            $this->connect = pg_connect("host=" . $dbhost . " port=" . $dbport . " dbname=" . $dbname . " user=" . $dbuser . " password=" . $dbpass);

            $this->executeAction();
        }

        // action router
        function executeAction() {
            if($this->action == "getEvents")
                $this->getEvents();
            else if($this->action == "moveEvent")
                $this->moveEvent();
            else if($this->action == "insertEvent")
                $this->insertEvent();
            else if($this->action == "updateEvent")
                $this->updateEvent();
            else if($this->action == "getCalendars")
                $this->getCalendars();
            else if($this->action == "toggleCalendar")
                $this->toggleCalendar();
            else if($this->action == "deleteCalendar")
                $this->deleteCalendar();
            else if($this->action == "insertCalendar")
                $this->insertCalendar();
        }

        // getEvents
        function getEvents() {
            //...
        }

        // moveEvent
        function moveEvent() {
            //...
        }

        // insertEvent
        function insertEvent() {
            //...
        }

        // updateEvent
        function updateEvent() {
            //...
        }

        // toggleCalendar
        function toggleCalendar() {
            //...
        }

        // deleteCalendar
        function deleteCalendar() {
            //...
        }

        // insertCalendar
        function insertCalendar() {
            //...
        }

    }

    // call class
    if(isset($_GET['action']))
        $instance = new calendarModel($_GET['action']);
    else
        $instance = new calendarModel();
?>

我想知道的是,我可以以某种方式从字符串名称中调用contruct中的操作,而不是在名为executeAction的函数中使用大的if / else。提前谢谢你,丹尼尔!

3 个答案:

答案 0 :(得分:4)

如果使用将使用函数名的表达式,则表达式的值将用作函数名:

function executeAction() {
    $this->{$this->action}();
}

由于您是从用户输入获取操作,请确保验证它。否则,有人可以发送使您执行任意方法的输入。

答案 1 :(得分:1)

使用类似的东西:

function __construct($action = "getEvents")
{
    ...
    $this->$action();
}

由于$ action是由用户定义的,您可能需要检查$ action是否是您班级中的现有函数:

if (array_key_exists($action, get_class_methods($this))) {
    $this->$action();
}

答案 2 :(得分:0)

巴马尔几乎是正确的: $这 - &GT; {$动作}();