没有评估的PHP动态鸭子打字

4 php duck-typing eval

例:

<?php
class a{
    public function func(){
        return "a";
    }
}

class b{
    public function func(){
        return "b";
    }
}

$input = "a"; // Would come from user input

eval('$duck = new '.$input.'();');
$duck->func(); // Returns a in this case
Run Code Online (Sandbox Code Playgroud)

有没有办法我可以不使用eval()

Ja͢*_*͢ck 8

当然你可以不用eval().PHP将把包含类名的字符串或文字作为new运算符的参数.

$duck = new $input; // parentheses are optional
echo $duck->func();
Run Code Online (Sandbox Code Playgroud)

  • 我已经编写了近一年的PHP编程,并且PHP OOP大约一个月.我从没想过会那么容易. (2认同)