我有一個字符串包含類名,我希望得到一個常量,並從該類調用(靜態)方法。從字符串訪問類常量和靜態方法
<?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();
不起作用。
在問我嘗試過什麼之前;我已經嘗試了很多我基本忘記的東西。
這樣做的最佳方法是什麼?提前致謝。
並且怎麼樣的方法? – 2012-02-21 15:53:42
更新了答案! Powe! – Rijk 2012-02-21 15:58:47
Pow!快速和簡單的答案,就像一個魅力。謝謝! – 2012-02-21 16:07:23