gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 22:53:50 25 4
gpt4 key购买 nike

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

<?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/

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