Tôi có một chuỗi chứa tên lớp và tôi muốn nhận một hằng số và gọi phương thức (tĩnh) từ lớp đó.Lớp truy nhập hằng số và phương thức tĩnh từ chuỗi
<?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;
}
}
?>
Như tôi đã dự kiến (nhiều hơn hoặc ít hơn), sử dụng $variable::CONSTANT
hoặc $variable::method();
không hoạt động.
Trước khi hỏi những gì tôi đã thử; Tôi đã thử rất nhiều thứ về cơ bản tôi quên.
Cách tiếp cận tốt nhất để làm điều này là gì? Cảm ơn trước.
Và những gì về phương pháp này? –
Đã cập nhật câu trả lời! – Rijk
Pow! Câu trả lời nhanh và dễ làm việc như một sự quyến rũ. Cảm ơn! –