Why is my constructor still called even if the class and constructor case are different?

前端 未结 4 1861
伪装坚强ぢ
伪装坚强ぢ 2020-12-21 01:58

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 Regi         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-21 02:29

    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:

    class Dog{
    
        function dog(){
            echo "Constructor is called.";
        }
    }
    
    $obj = new Dog();
    $obj->dog();
    

提交回复
热议问题