twigg twigg - 1 month ago 5x
PHP Question

php is the constructor called when each method is called?

Is the __construct method called every time you run a method in a class? Example:

class SomeClass {
function __construct() {
// do something

function a() {
// do something for a

So when I call the class

$class = new SomeClass();

I believe the constructor is run? But how about when I do something like the following:

echo $class->a();

Is the constructor run again at this point?


No. As stated here:

Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.

In the end, constructors implicitly called only when you creating object. So in your example:

$class = new SomeClass();
//       ^ triggers constructor
echo $class->a()
//       ^ not triggering constructor but have to be initialized before usage