What is the purpose of the initial function in a PHP class that has the same name as the class?

I'm starting with OO PHP, and after looking at the various classes that I downloaded from the Internet, I noticed that some, but not all, of these classes have a built-in function with the same name, for example

class MyClass{

function MyClass{

//function contents in here

}

function otherfunction{

//more stuff here

}

}

What is this function for? And how does this help when writing classes?

+3
source share
4 answers

This is an old constructor. If you are using PHP 5 (you should), you should avoid these constructors and instead:

class MyClass{

    function __construct() {
        //function contents in here
    }

    function otherfunction() {
        //more stuff here
    }
}

Constructors, in short, are used to run initialization code and to ensure that class invariants are used.

+5
source

- , ,

0
0

, . , Bark() , Bark - , .

(, , ), bark(), , (. THING COMMAND? ( Bark bark())).

, :

BarkBehaviour {  public function bark(); }

Bark BarkBehaviour {   ()  { echo "\nWoof!";  } }

an instance of your dog's barkBehaviour property will echo "Woof" because PHP considers the bark () method to be the constructor of the Bark class, which you did NOT intend this way. In JAVA, these things are case sensitive, so the Bark class constructor should be called Bark (), not bark ().

0
source

Source: https://habr.com/ru/post/1750812/


All Articles