It's very common to execute a piece of code when an object is created. In this lesson, you'll learn how to do just this with a PHP class constructor.
Instructor: [0:00] We can execute a bit of code that runs at the time objects are being created, with a special piece of functionality called a constructor. Constructors are a built-in PHP feature at the language level and use what's known as a magic method, which are always prefixed with two underscores.
[0:20] Let's create a constructor within our Author class by creating a new public function named __ construct. Within this function we will output a string, just to let us know that this constructor was executed. Let's call var_dump and we will pass in "Author Class Instantiated."
[0:49] Now, when we save and refresh our page, we will see that string being outputted, so we know this constructor is executing. This magic method will execute or run every time a new instance of a class is created with the new keyword.
[1:06] Related to that, functions within classes are also referred to as class methods, not functions. You may hear the terms methods and functions used interchangeably. They're generally the same thing.
[1:21] We can also pass values into constructors. I'm going to pass my name, Mark Shust, into this class object within the parentheses as a string. Let's pass "Mark Shust." Now we will create a method argument to assign to the string, which can be any arbitrary value. If you are using PhpStorm, you can also Command- or Alt-Click into the class to go directly to it.
[1:52] Let's assign the string the value of $name. Rather than dumping out this Author Class Instantiated string, we will just output the name variable. When we refresh our page, we can see that the argument is being passed into this constructor and being outputted.
[2:12] We can use this approach any time we wanted to create an object with a specific value or property, and then do something to it later on in our code.