Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Can someone explain to me Constructor Method ?

Im not sure how the Constructor Method works as when you echo out your not applying or calling anything in to the Constructor Method ?

2 Answers

Pere Grau
Pere Grau
7,750 Points

As I understand, the code inside the constructor method in a class is called every time that you call a method of that class. I'll put an example:

Imagine that you have a class named ClassA with a constructor method and three other methods: method1, method2, and method3. Every time you call a method, the code inside the constructor will be executed before the code of that method itself. So, having this:

$class = new ClassA();
$class->method1();

It will first execute the code inside the constructor and then the code inside method1. Well, at least this is how I see it.

Hope it helps! Cheers!

Its making a instance of a object

For example, If you had a dog object, you would want to make a constructor to have him bark or his breed or color or something like that