2 回答
TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以做到這一點(diǎn)的一種方法是使用 class_exists,如果它不存在,則添加一個(gè)虛擬占位符。
但理想情況下,我建議您研究 Laravel 使用的 Facades。通過(guò)這種方式,您可以靈活地實(shí)現(xiàn),而無(wú)需依賴?yán)^承。
在線查看https://ideone.com/pWf8QU
/* // unhide this to see the two behaviours
class ReplacementClass {
public function foo() {
return "foo";
}
public function bar() {
return "bar";
}
}*/
if(!class_exists('ReplacementClass')) {
class MyReplacementClass {
public function foo() {
echo " foo does not exist, this is a placeholder";
}
public function bar() {
echo " bar does not exist, this is a placeholder";
}
}
}
else {
class MyReplacementClass extends ReplacementClass {
}
}
class FooBar extends MyReplacementClass {
}
$x = new FooBar();
echo $x->foo() . $x->bar() . "\n";
TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以為此使用eval()。但這很臟。
eval("class $className extends $parentClassName {}");
例子
class Foo {}
$className = 'Bar';
$parentClassName = 'Foo';
eval("class $className extends $parentClassName {}");
$bar = new Bar();
var_dump($bar); // gives 'object(Bar)#1 (0) {}'
var_dump($bar instanceof Bar); // gives bool(true)
var_dump($bar instanceof Foo); // gives bool(true)
警告!使用 eval 效率低下并且可能非常危險(xiǎn)。在考慮使用它之前,請(qǐng)先查閱文檔。
最好重新考慮您的用例。從字面上看,我想不出什么需要完全動(dòng)態(tài)的類名。如果此時(shí)您將庫(kù)導(dǎo)入代碼庫(kù),您應(yīng)該知道預(yù)期的類名,此時(shí)您可以使用該名稱的類擴(kuò)展您的父類。
- 2 回答
- 0 關(guān)注
- 146 瀏覽
添加回答
舉報(bào)
