gpt4 book ai didi

php - 声明和调用名称中带有句点的 PHP 对象函数

转载 作者:行者123 更新时间:2023-12-02 07:45:08 25 4
gpt4 key购买 nike

我正在使用返回不同值的 API,并且我想动态地告诉我的类运行具有相同名称的函数(因此我不需要巨大的 switch if/else 困惑)。

  1. 如何声明对象方法song.pause
  2. 如何使用对象方法song.pause
  3. 这可能是 XY Problem ,那么有没有更好的方法来做到这一点呢?我想到的一种替代方法是始终调用 str_replace('.','_',$type) 并设置不带句点的函数。有什么想法吗?

示例:

<?php
class MyClass {
...
...
$type = "song.pause"; // This value is returned from another API I can't control

if (property_exists('MyClass', $type)) {
$success = $this->{$type}(); // ???
} else {
header("HTTP/1.1 400 Invalid type: $type);
exit;
}


public function 'song.pause'() { // obviously incorrect :)
???
}

最佳答案

鉴于返回 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.

关于php - 声明和调用名称中带有句点的 PHP 对象函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25615206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com