为什么类定义中不能有 require* 语句?
可能相关:
为什么 PHP 属性不允许使用函数?
如果有人问这个问题,请原谅我之前,但为什么你不能有如下内容:
class foo {
require_once 'defines.php';
private $_server = DB_SERVER;
private $_username = DB_USERNAME;
private $_password = DB_PASSWORD;
private $_database = DB_NAME;
public $debug = false;
public $_conn;
function __construct() {
$connection = @mysqli_connect($this->_server, $this->_username, $this->_password, $this->_database);
}
...
}
干杯,
编辑:希望找出为什么这种行为存在以及为什么它不可能。 投票怎么就结束了?
EDIT2:也想重新打开此
Possibly Related:
Why don't PHP attributes allow functions?
Pardon me if this has been asked before, but why can you not have something like the following:
class foo {
require_once 'defines.php';
private $_server = DB_SERVER;
private $_username = DB_USERNAME;
private $_password = DB_PASSWORD;
private $_database = DB_NAME;
public $debug = false;
public $_conn;
function __construct() {
$connection = @mysqli_connect($this->_server, $this->_username, $this->_password, $this->_database);
}
...
}
Cheers,
EDIT: Looking to find out why this behaviour exists and why its not possible.
How come the votes to close?
EDIT2 : Would also like to re-open this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在将类添加到 PHP 之前,可以在函数作用域和全局作用域内
require
和include
文件。这只是一个猜测——我不确定除了让语言设计者来告诉我们他们的故事之外我们还能做什么——但我想人们相信将这个功能添加到“新的”中不会获得任何好处。通过添加类而发明的“范围”,特别是考虑到为了支持它而添加到后端的复杂性。
对于
require
d 文件内所做的任何声明的范围规则也并不完全清楚。总之,我认为你问了错误的问题。而不是“为什么不支持这个?”这更多的是“为什么应该支持它?”的情况。
我希望这能在一些小方面有所帮助。
It was possible to
require
andinclude
files both within function scope and at global scope, before Classes were added to PHP.This is only a guess — I'm not sure what else we could do other than for the language designers to come and tell us their story — but I imagine it was believed that no benefit would be gained from adding this functionality to the "new scope" invented by the addition of Classes, especially considering the complexity added to the back-end in order to support it.
It's also not entirely clear what the scoping rules would be for any declarations made inside the
require
d file.In conclusion, I think you're asking the wrong question. Instead of "why isn't this supported?" it's more a case of "why should it be supported?".
I hope that this helps in some small way.
这是因为在类定义中根本不允许“真实”代码,只允许属性、方法和常量的定义。您可以将包含语句放入“主范围”(过程)、函数和方法中,就像其他代码一样。
但是,据我所知,任何语言都不支持它。例如,java 为此使用静态代码块。
在 PHP 中,只需将“静态”代码放在类本身之后即可。
无法以这种方式访问
private
或protected
static
成员。It is because in the class definition "real" code is not allowed at all, only definitions for properties, methods and constants are allowed. You can put your include-statements into "main-scope" (procedural), functions and methods, like every other code.
However, as far as I know its not supported in any language. For example java uses static code blocks for this
In PHP just put your "static" code after the class itself.
Its not possible to access
private
orprotected
static
members this way.