php - 从字符串访问类常量和静态方法

标签 php string class methods static

我有一个包含类名的字符串,我希望获得一个常量并从该类调用一个(静态)方法。

<?php
$myclass = 'b'; // My class I wish to use

$x = new x($myclass); // Create an instance of x
$response = $x->runMethod(); // Call "runMethod" which calls my desired method

// This is my class I use to access the other classes
class x {
    private $myclass = NULL;

    public function __construct ( $myclass ) {
        if(is_string($myclass)) {
            // Assuming the input has a valid class name
            $this->myclass = $myclass;
        }
    }

    public function runMethod() {
        // Get the selected constant here
        print $this->myclass::CONSTANT;

        // Call the selected method here
        return $this->myclass::method('input string');
    }
}


// These are my class(es) I want to access
abstract class a {
    const CONSTANT = 'this is my constant';

    public static function method ( $str ) {
        return $str;
    }
}

class b extends a {
    const CONSTANT = 'this is my new constant';

    public static function method ( $str ) {
        return 'this is my method, and this is my string: '. $str;
    }
}
?>

如我所料(或多或少),使用 $variable::CONSTANT$variable::method(); 不起作用。

在询问我尝试了什么之前;我已经尝试了很多我基本上忘记的东西。

执行此操作的最佳方法是什么?提前致谢。

最佳答案

要访问常量,请使用 constant() :

constant( $this->myClass.'::CONSTANT' );

请注意:如果您正在使用命名空间,即使您从同一个命名空间调用 constant(),也需要专门将您的命名空间添加到字符串中!

对于通话,您必须使用 call_user_func() :

call_user_func( array( $this->myclass, 'method' ) );

但是:这一切都不是很有效,因此您可能需要重新审视您的对象层次结构设计。可能有更好的方法来实现预期的结果,例如使用继承等。

关于php - 从字符串访问类常量和静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9380562/

相关文章:

java - 对象相等(对象引用 "==")

c++ - 如何检查字符串中的关键字c++

jquery - 如何在 jQuery 中获取具有特定类名的 <span> 元素?

c++如何创建相互依赖的类

javascript - 如何使用 JS 在 iframe 中运行可编辑的 PHP?

javascript - ajax 请求使页面滞后

PHP 字符串帮助

php - 将数组数据准备到另一个结构以使用某些规则呈现定义的 HTML 输出的算法

r - 生成字符变量作为ID变量

python - 我需要帮助修复 __str__ 方法。不返回任何东西