在名称中声明和调用PHP对象函数

时间:2014-09-02 02:58:35

标签: php oop

我使用的API返回不同的值,我想动态告诉我的班级运行一个同名的函数(所以我不需要一个巨大的switch或{ {1}}混乱)。

  1. 如何声明对象方法if/else
  2. 如何使用对象方法song.pause
  3. 这可能是XY Problem,那么有更好的方法吗?我想到的另一个选择是始终调用song.pause并设置没有句点的函数。想法?
  4. 示例:

    str_replace('.','_',$type)

3 个答案:

答案 0 :(得分:3)

如果返回song.pause,概念上song应该是类名,pause应该是方法,请考虑这种可能性:

class MyClass {
    protected $classes = array();

    function processResponse($response) {
        // $response example is "song.pause"
        list($class, $method) = explode('.', $response);
        if(!class_exists($class)) {
            // Class doesn't exist
            die("Class name {$class} doesn't exist! Exiting...");
        }

        // Instantiate class
        $this->classes[$class] = new $class();

        if(!method_exists($this->classes[$class], $method)) {
            // Method doesn't exist within specified class
            die("Method name {$method} doesn't exist within {$class}. Exiting...");
        }

        // Call method
        $result = $this->classes[$class]->{$method}();

        return $result;
    }
}

您的逻辑实现将是这样的:

class song {
    public function pause() {
        return 'foobar';
    }
}

Here's an example.

答案 1 :(得分:2)

不幸的是,您通常会问的是不支持。来自manual

  

函数名称遵循与PHP中其他标签相同的规则。一个有效的   函数名称以字母或下划线开头,后跟任何字符   字母,数字或下划线的数量。作为正则表达式,   它将如此表达:[a-zA-Z_ \ x7f- \ xff] [a-zA-Z0-9_ \ x7f- \ xff] *。

这也适用于类方法。

作为解决方案,您可以按照自己的建议方式:

$type = 'song.pause';
$type = str_replace('.', '_', $type);
$this->{$type}(); // will call song_pause()

或使用"dark" magic

<?php
// header('Content-Type: text/plain; charset=utf-8');

class Test {
    function __call($method, $args){
        // do redirect to proper processing method here
        print_r($method);
        echo PHP_EOL;
        print_r($args);
    }
}

$x = new Test();
$x->{'song.pause'}(1,2,3);
?>

节目:

song.pause           // < the method
Array                // < arguments
(
    [0] => 1
    [1] => 2
    [2] => 3
)

然而,我完全同意的是“长”且非常透明的方式,is suggested by @scrowler

答案 2 :(得分:2)

@ HAL9000是对的:不支持您想要的内容。一个潜在的解决方法是:

定义处理程序:

$typeHandlers = array();
$typeHandlers['song.pause'] = function () {
    echo 'Pause!'; // or whatever...
};

调用适当的处理程序:

$typeHandlers[$type]();