繁体   English   中英

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

[英]Access class constant and static method from string

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

<?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 7 中,您可以使用此代码

echo 'my class name'::$b;

要么

#Uncomment this lines if you're the input($className and $constName) is safe.
$reg = '/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$/';
if(preg_match($reg,$className) !== 1 || preg_match($reg,$constName) !== 1)
    throw new \Exception('Oh, is it an attack?');
$value = eval("return $className::$constName;");

您可以通过设置临时变量来实现它。 不是最优雅的方式,但它有效。

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

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

我想这与::的歧义有关,至少是错误消息所暗示的( PHP Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

使用call_user_func调用静态方法:

call_user_func(array($className, $methodName), $parameter);

这可能与主题无关,但是,在寻找我自己的问题时,我发现接受的答案为我指明了正确的方向,因此我想分享我的问题和解决方案,以防其他人可能陷入类似的困境。

我正在使用 PDO 类并从 ini 配置文件构建一些错误选项。 我需要它们在以下形式的关联数组中: PDO::OPTION_KEY => PDO::OPTION_VALUE ,但它当然失败了,因为我试图仅使用PDO::$key => PDO::$value构建数组.

解决方案(灵感来自接受的答案):

$config['options'] += [constant('PDO::'.$key) => constant('PDO::'.$option)];

如果您将类名和作用域解析运算符连接为带有变量的字符串,并通过常量函数获取结果字符串的常量值(更多在这里),则一切正常。 谢谢你,我希望这能帮助别人!

定义为抽象的类不能被实例化,任何包含至少一个抽象方法的类也必须是抽象的。 定义为抽象的方法只是声明方法的签名——它们不能定义实现。

从抽象类继承时,父类声明中所有标记为抽象的方法必须由子类定义; 此外,这些方法必须定义为具有相同(或较少限制)的可见性。 例如,如果抽象方法被定义为受保护,则函数实现必须被定义为受保护或公共,但不能被定义为私有。 此外,方法的签名必须匹配,即类型提示和所需参数的数量必须相同。 这也适用于 PHP 5.4 起的构造函数。 5.4 之前的构造函数签名可能不同。 参考http://php.net/manual/en/language.oop5.abstract.php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM