【发布时间】:2012-03-11 22:34:34
【问题描述】:
我有一个包含类名的字符串,我希望获取一个常量并从该类调用一个(静态)方法。
<?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(); 不起作用。
在问我尝试过什么之前;我已经尝试了很多我基本上都忘记了的东西。
最好的方法是什么?提前致谢。
【问题讨论】:
标签: php string class methods static