PHP - OOP - Why is my function called twice?

前端 未结 5 1139
逝去的感伤
逝去的感伤 2021-01-17 05:00

I\'m facing a problem that my function is called twice everytime i submit my form

my form file with the call to the function:



        
相关标签:
5条回答
  • 2021-01-17 05:39

    Your class name is login. You do not have __construct(), and you have a function called login(). So when you instantiate the class, login() is called first since you did not define __construct() , method name same as class becomes the constructor. Then you are calling the login() function again. Hence its called twice.

    0 讨论(0)
  • 2021-01-17 05:46

    A method named the same as the class is considered an (old style) constructor, and is called every time the object is created.

    So it's called once when the object gets created, and another time when you explicitly call it.

    Note that today, it's considered a better practice to implement __construct() rather than ClassName(), mainly to help with inheritance.


    More reading material:

    • PHP - Constructors and Deconstructors
    • PHP - Old Style Constructors
    0 讨论(0)
  • 2021-01-17 05:53

    In PHP 4 the constructor of a class had the same name as the class. When in PHP 5 destrutors were added the naming scheme __construct() was added, the old way was kept working for compatibility reasons, though.

    In your case this means that login() will first be called as constructor, then from the explicit call

    0 讨论(0)
  • 2021-01-17 05:54

    When you create a Class, you should specify a Constructor.

    If you dont specify a Constructor, it's called by Magic Methods.

    In Your Case, you create a Class Without a constructor, by with a function with the same name of the Class. Class Login -> Method Login. The PHP Acts like the Login Method is your constructor...

    So when you call $login = new Login() you are calling the constructor that's the Login Method.

    And when you call Login Method, $login->login(), you are calling it twice.

    Are you understood?

    0 讨论(0)
  • 2021-01-17 05:55

    You call one time the function with the constructor, seconde time manually. In PHP 5.3.3, if you name function like the class, it's a constructor.

    0 讨论(0)
提交回复
热议问题