如果我像这样创建类的实例
$template = new EmailTemplate(array('templateFile' =>'template__test.php'));
为什么以下回显NULL
?
class EmailTemplate {
private $templateFile;
function __construct($args) {
foreach($args as $key => $val) {
if(property_exists($this, $this->{$key})) {
$this->{$key} = $val;
}
echo $this->templateFile;
}
}
我期待构造函数回应" template__test.php"。
任何帮助?
答案 0 :(得分:1)
你应该像这样调用构造函数:
class EmailTemplate {
private $templateFile;
function __construct( $args ) {
// Loop through the arguments
foreach ( $args as $key => $val ) {
// Check if the current class has a defined variable
// named as the value of $val
if ( property_exists( $this, $key ) ) {
// If it has, set it to the passed value
$this->$key = $val;
// If you pass multiple array items, you should echo $this->$key;
}
// Print the defined variable to screen
echo $this->templateFile;
}
}
}