即使类和构造函数的情况不同,为什么我的构造函数仍然被调用?
我很惊讶为什么当我们有不同的类和构造函数名称时调用构造函数。构造函数名称以小写“r”开头?
class Registration{
function registration(){
echo "Constructor is called.";
}
}
$obj = new Registration();
//$obj->registration();
输出: 构造函数被调用。
修改: 这种不区分大小写的行为是否取决于我们使用的 php 版本?
I am surprised for why the constructor is called when we have different class and constructor name. Constructor name is starting with small "r"?
class Registration{
function registration(){
echo "Constructor is called.";
}
}
$obj = new Registration();
//$obj->registration();
Outputs:
Constructor is called.
Modification:
Does this case-insensitive behavior depends on php versions we are using?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
php 不区分大小写(有时)。以下内容也可以工作:
php is case-insensitive (sometimes). The following would work as well:
在 php 中,所有函数名称都不区分大小写。
顺便说一句,您应该切换到 新样式
__construct
。作为具有类名称的函数的构造函数是历史产物。In php, all function names are case-insensitive.
By the way, you should switch to the new-style
__construct
. Constructors as functions with the name of the class are a historical artifact.我认为这两个名称是相同的..
因为当您尝试在同一页面中声明名称为“registration”的类时,它会给您一个错误,指出您无法重新声明该类..
在这种情况下,它不是区分大小写
I think both names are same ..
because when you try to declare the class with name "registration" in same page, it will give you an error that states that you can not re declare the class..
in this case , it is not case sensitive
PHP 不区分大小写,但这并不能解释其行为。
此行为是因为与类同名的函数被视为构造函数。
请参阅http://php.net/manual/en/language.oop5.decon。 php - 示例 2
因此,对于任何给定名称 EG 的函数都是如此:
PHP is case insensitive, but this doesn't explain the behaviour.
This behaviour is because a function with the same name of the class is treated as the constructor.
See http://php.net/manual/en/language.oop5.decon.php - Example 2
So this is true for functions of any given name, EG: