![](/img/trans.png)
[英]Why can you instantiate a class from a string variable but not a string in PHP?
[英]Can PHP instantiate an object from the name of the class as a string?
如果類名存儲在字符串中,是否可以在 PHP 中從類名實例化一個對象?
是的,絕對。
$className = 'MyClass';
$object = new $className;
<?php
$type = 'cc';
$obj = new $type; // outputs "hi!"
class cc {
function __construct() {
echo 'hi!';
}
}
?>
如果您的班級需要參數,您應該這樣做:
class Foo
{
public function __construct($bar)
{
echo $bar;
}
}
$name = 'Foo';
$args = 'bar';
$ref = new ReflectionClass($name);
$obj = $ref->newInstanceArgs(array($args));
也是靜態的:
$class = 'foo';
return $class::getId();
您可以通過將類名/方法存儲在數據庫等存儲中來進行一些動態調用。 假設該類對錯誤具有彈性。
sample table my_table
classNameCol | methodNameCol | dynamic_sql
class1 | method1 | 'select * tablex where .... '
class1 | method2 | 'select * complex_query where .... '
class2 | method1 | empty use default implementation
等等。然后在您的代碼中使用數據庫為類和方法名稱返回的字符串。 你甚至可以為你的類存儲 sql 查詢,自動化程度是否達到你的想象。
$myRecordSet = $wpdb->get_results('select * from my my_table')
if ($myRecordSet) {
foreach ($myRecordSet as $currentRecord) {
$obj = new $currentRecord->classNameCol;
$obj->sql_txt = $currentRecord->dynamic_sql;
$obj->{currentRecord->methodNameCol}();
}
}
我使用這種方法來創建 REST Web 服務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.