为什么在php类中作为数组项不起作用 [英] Why function as array item in php class doesn't work
问题描述
<?php
$ A = array(
'echoSmth'=> function(){
echo'Smth';
}
);
$ A ['echoSmth'](); //'Smth'
?>
工作正常!
但是如果$ A不仅仅是一个变量,而是一个Class方法 - 比这不行:
<?php
class AA {
public $ A = array(
'echoSmth'=> function(){//解析错误! b $ b echo'Smth';
}
);
}
//固定呼叫:
$ t = new AA();
$ t-> A ['echoSmth']();
//不管是什么调用,因为错误发生得早 - 在描述类
?>
为什么它不起作用?
它显示:
解析错误:语法错误,意外的T_FUNCTION
对不起,我用我称呼该方法的方式犯了一些错误,我很着急。但不管我怎么打电话。错误ocurrs,即使我只是声明类,而不调用 解决方案
据我所知,你不能有任何东西动态定义类成员时,可以按照以下方式动态设置它。所以基本上,你不能这样做,因为你不能这样做: public $ A = functionname();
另外,您的通话签名不正确,我已经在我的示例中修复了它。
< ?php
class AA {
public $ A = array();
public function __construct(){
$ a = function(){
echo'Smth';
};
$ this-> A ['echoSmth'] = $ a;
}
}
$ t = new AA();
$ t-> A ['echoSmth']();
或者,您可以在 __ construct()
,包含该方法(所以基本上转移你的代码)。
For example, I have such a code:
<?php
$A = array(
'echoSmth' => function(){
echo 'Smth';
}
);
$A['echoSmth'](); // 'Smth'
?>
It works fine! But If $A is not just a variable, but a Class method - than this doesn't work:
<?php
class AA {
public $A = array(
'echoSmth' => function(){ // Parse Error here!
echo 'Smth';
}
);
}
// Fixed call:
$t = new AA();
$t->A['echoSmth']();
// no matter what call, because error occurs early - in describing of class
?>
Why doesn't it work?
It displays:
Parse error: syntax error, unexpected T_FUNCTION
P.S. Sorry, I've made some mistakes in the way I call the method, I was in hurry. But there's no matter how I call. Error ocurrs even if I just declare class, without calling
As far as I'm aware, you can't have anything dynamic when defining a class member, you can however set it dynamically as below. So basically, you can't do it for the same reason that you can't do this: public $A = functionname();
Also, your call signature was incorrect, I've fixed it in my example.
<?php
class AA {
public $A = array();
public function __construct() {
$a = function() {
echo 'Smth';
};
$this->A['echoSmth'] = $a;
}
}
$t = new AA();
$t->A['echoSmth']();
Alternatively, you could define the whole array within __construct()
, containing the method (so basically shift your code).
这篇关于为什么在php类中作为数组项不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!