为什么自动调用与该类同名的方法

为什么自动调用与该类同名的方法

本文介绍了为什么自动调用与该类同名的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题经过编辑,使其更有用.最初,我不知道是使用共享词引起了问题.

Title edited to make it more useful. Originally I had no idea that it was the use of a shared word that was causing the problem.

这是非常基本的,但是相当神秘.

This is very basic but rather mysterious.

我有两节课:

class Hello
{
        public function hello()
    {
        echo "Hello";
    }
}

class World
{
    public function world()
    {
        echo " World";
    }
}

include_once 'classes/Hello.php';
include_once 'classes/world.php';

$hi= new Hello;
$wd= new World;`

结果Hello World

我最初不小心将hello用作类World的方法的名称.结果Hello,即否World.

I originally accidentally had hello for the name of the class World's method.Result Hello i.e. no World.

问题1

为什么会触发这些方法?我已经实例化了两个对象,但是没有请求方法"fire".我以为我必须做这样的事情:

Why are the methods firing? I have instantiated two objects but have not requested that the method "fire". I thought I would have to do something like:

$hi->hello();

获得输出.

问题2

让我更加困惑的是,只有两个函数都被称为hello时,我才会得到Hello.

I am even more mystified that I only get Hello if both functions are called hello.

当然

$hi= new Hello;
$wd= new World;

实例化两个完全独立的对象.那么,方法的实际名称如何影响任何东西?

instantiates two completely separate objects. So how does the actual NAME of a method affect anything?

我还有很长的路要走,但这确实让我感到困惑.

I have a long way to go but this really confused me.

推荐答案

在创建此类的新实例时,这两种方法都会被调用,因为这些方法与类本身具有相同的名称,因此它们是构造函数:

Both methods get called, when you create a new instance of this class, because the methods have the same name as the class itself and so they are the constructor of this class:

class Hello
{
        public function hello()
    {
        echo "Hello";
    }
}
class World
{
    public function world()
    {
        echo " World";
    }
}

因此,当您从两个类中获取一个实例时,两个构造函数都被调用.

So when you took an instance from both classes, both constructors got called.


现在,当您将两个方法都重命名为hello时,只有一个方法被视为构造方法,而另一个方法在另一个类中是普通方法.这就是为什么您只看到Hello作为输出的原因.

Now when you renamed both methods to hello only 1 method was counted as constructor and the other one was a normal method in the other class. That's why you only saw Hello as output.

但是不要将类的名称用作构造函数! 它将在PHP 7中弃用.使用__construct().

But don't use the name of the class as constructor! It will be deprecated in PHP 7. Use __construct().

这篇关于为什么自动调用与该类同名的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:57