Sign In | Subscribe
Start learning today, and be successful in your academic & professional career. Start Today!
Loading video...
This is a quick preview of the lesson. For full access, please Log In or Sign up.
For more information, please see full course syllabus of Advanced PHP
  • Discussion

  • Study Guides

  • Download Lecture Slides

  • Table of Contents

  • Transcription

  • Related Services

Bookmark and Share

Start Learning Now

Our free lessons will get you started (Adobe Flash® required).
Get immediate access to our entire library.

Sign up for

Membership Overview

  • Unlimited access to our entire library of courses.
  • Search and jump to exactly what you want to learn.
  • *Ask questions and get answers from the community and our teachers!
  • Practice questions with step-by-step solutions.
  • Download lesson files for programming and software training practice.
  • Track your course viewing progress.
  • Download lecture slides for taking notes.
  • Learn at your own pace... anytime, anywhere!

Object Constructors

  • A constructor is a special object method that gets called automatically each time a new instance of a class is instantiated.
  • Constructors are used to perform any initialization tasks that need to be done before an object is ready to be used, such as providing default values for all of an object’s properties.
  • In PHP 5, constructors are known as magic methods and must be named __construct(). They are defined within a class definition just like any other object method.
  • Arguments are provided to an object’s constructor method by specifying them between the parentheses following the class name when an object is created using the new keyword:
    $person1 = new Person(‘Joe’, ‘Smith’);
  • A class is not required to have a constructor method.
  • Unlike other programming languages, only one constructor method can be defined per PHP class.
  • Additional Resources:

Object Constructors

Lecture Slides are screen-captured images of important points in the lecture. Students can download and print out these lecture slide images to do practice problems as well as take notes while watching the lecture.

  • Intro 0:00
  • Lesson Overview 0:11
    • Lesson Overview
  • Object Constructors 0:32
    • Introduction to Object Constructors
    • Coding Example: Object Constructors
  • Defining Constructors 3:26
    • Defining Constructors
    • Coding Example: Constructors with No Arguments
  • Constructor Arguments 8:09
    • Constructor Arguments
    • Coding Example: Constructor Arguments
  • Important Notes 16:13
    • Important Notes
  • Homework Challenge 17:35
    • Homework Challenge: 1 - 4
  • Homework Challenge (cont.) 19:13
    • Homework Challenge: 5 - 9
  • Homework Challenge (cont.) 21:40
    • Homework Challenge: 10 and 11

Transcription: Object Constructors

Hello again, and welcome back to's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be covering the topic known as object constructors, which are a special type of object methods.0005

We are going to go over what an object constructor is.0012

We are going to talk about how to define constructors within your class definitions.0016

We are going to talk about how to specify arguments to constructors, and then just go over some important notes,0022

as they relate to using constructors in PHP.0028

In object-oriented programming, a constructor is a special object method that is called every time you create a new instance of an object.0034

For example, if we go back to our typical Person class, every time we create a new instance of the Person class,0045

using this new keyword, a special object method for the Person class, called a constructor, gets executed.0057

And it is done automatically by PHP.0066

It is a special kind of method; you don't actually have to define one, but if you do (which is what we are going to go over in this course),0071

it has to have this special name here: and constructors in PHP 5 (which is what we are working with) are known as magic methods.0076

And that means they have some special meaning in PHP.0087

In this case, it means it is something that PHP knows to call automatically.0089

And any time you see a method with two underscores before the name of it, that is reserved as a magic method.0093

And we will talk more about that in a future lesson--about what magic methods are.0099

For example, let's take a look at Person.php.0104

And we are going to go more into the details in a second.0110

This is an object method that is a constructor for this Person object.0112

It is defined just as you would any other method, except it has to have this special name.0120

It has to have this name: two underscores, followed by the word construct, and then parentheses.0124

And just to show you that inside our constructor, it doesn't do anything: it is a function that can do pretty much anything other functions can do...0129

We are going to echo a statement that says we are inside this Person constructor,0137

so we know that this method is being executed--because we never actually call this construct method directly.0140

So, to let you know what is going on behind the scenes, we are going to demonstrate that.0149

And all we are going to do is: in this simpleConstructor.php script, we are going to just instantiate a new instance of this Person class.0153

Now, because we have defined a constructor for it, PHP is automatically 0162

going to run that constructor every time this new keyword defines a new instance of the class.0165

And because that constructor is going to get run, it is going to output the message.0171

If we go and look at this script simpleConstructor.php, we can see that it outputs the message "inside Person constructor."0176

Even though we never actually explicitly called, for example, Person __construct, like we would another object method,0188

it gets done every time this new statement is executed.0198

Constructors can be defined just like any other object method.0208

As we mentioned, they have to have this specific name here to be called automatically.0211

One thing they can't do is return a value; but as far as methods go, they can do the same thing, pretty much, as other object methods and functions can do.0216

They can accept parameters, and they can perform operations within them.0225

Typically, a constructor is used to perform initialization tasks that need to be done before an object is ready to use.0229

For example, when you have properties defined in a particular object, because that constructor gets called0239

every time a new instance of that object is created, you can use that as an opportunity to set default values for your properties,0245

or to maybe perform some other advanced functionality that you might need to do before a user can really use that object.0255

If we take a look at a new version of Person.php (which, again, just has a firstName and lastName property), here we have defined the constructor.0264

It takes no arguments; and we will talk about ones that can take arguments in a second.0278

And what this object method, this constructor, does, is: it initializes our firstName and lastName variables, just so that they have default values.0283

It is just going to initialize them to the empty string.0292

So, at least that way, if someone calls new Person, and then tries to access these variables,0295

it will at least return a string (in this case, the empty string), because a user of the Person class would be expecting a string to be returned.0301

If you will notice, again, as we have done in our other object methods: to access an object's properties from within an object method,0310

which a constructor is, you use the $this special variable.0317

So, if we go to our script called noArgConstructor, what it does is instantiates a new Person class.0322

And we don't do anything else with that Person; we don't set the values of any variables or anything like that.0331

We are not making any statements like this.0338

All we are doing is instantiating the class; and by default, that is automatically going to call that default constructor.0345

And then, what we are going to do is: down here, we are going to try and output those variables--those object properties, firstName and lastName.0352

Now, because this constructor has been called, they get set with the default variable of the empty string.0361

I just have a little test that we have created down here that tests if this instance of the Person object's firstName is equal to null,0366

which means it hasn't been initialized, because that is a default initialization value for variables in PHP.0380

Then, it is going to return the value of firstName.0387

Now, what it is going to do: this is a ternary operator, and it is going to set this firstName variable equal to that firstName value.0390

So, in this example, firstName has set a variable; it is set to the empty string.0398

It is not a string that has anything, but it is set to a string, so it is not null.0403

And otherwise, this is going to return the string null.0408

When we output firstName, if firstName hasn't been initialized, it is going to output null.0412

If it has been (which we know it has, from our constructor), it is going to output the empty string.0416

And we do the same thing down here for our lastName.0421

If we go and load this script in our browser, noArgConstructor.php, we can see that, when it tried to output firstName and lastName,0423

it output the empty string; and so, that means that the values were not equal to null.0434

Let's say, instead, that in our constructor, we didn't initialize, for example, the lastName variable; let's say we just removed that.0440

So, we only initialized firstName.0448

Because of that, lastName is never going to be initialized; it is not going to be a string; it is going to be set equal to null.0451

When we run our script, we are going to see lastName, and it is going to output the value null.0456

And so, that shows using a constructor to initialize variables.0462

And pretty much, that is what you are always going to want to do with your constructor.0468

You always want to give, for various reasons, default values to all of an object's properties.0471

And the main place you do that is within the constructor.0480

And we are going to see a little bit more about that on our next slide.0484

One thing that we noted is that constructors are methods; in that way, they can take parameters, just like any other object method or function can do.0491

And the way you provide objects to an object's constructor is by specifying them in between the parentheses0500

when you instantiate a new instance of the object.0508

Normally, when we call an object method, and we want to pass it two parameters, we would call the method name, and then pass it the parameters.0514

Because this is done automatically in PHP, what PHP knows to do is that, if you provide any parameters0527

between the parentheses in a statement where you are instantiating a new instance of an object (in this case, the Person object),0534

whatever is in parentheses are going to be passed as parameters to that constructor object.0542

So, you can define constructors that can accept multiple parameters.0546

They are placed in a comma-delimited list, just like any arguments you would supply to any other function or object method.0550

The only difference is just that you are not actually calling the method by its name; you are just using the name of the class.0558

And PHP, again, knows how to automatically pass those variables on to the construct method.0564

One thing that this is typically used for is, for example, our Person object.0571

The Person object has a first name and a last name; what you can do is use a constructor that requires two parameters.0576

And so, whatever values you pass it, it can use to set as the firstName and lastName of that Person, which is what constructors are commonly used for.0583

For example, if we look at our new version of Person.php, we can see that we have an updated constructor0590

that takes two parameters: one called firstName and one called lastName.0599

And then, it sets the value of our object property, firstName, equal to whatever value was passed in by the firstName parameter.0603

And it does the same thing for our lastName property: it sets the lastName property of this instance that this constructor is being called for.0612

And it sets it equal to the value that is passed into the constructor via lastName.0621

For example, now, when we call our constructor for Person, we can pass it two parameters.0628

We can pass it a first name and a last name--in this case, Joe Smith.0634

And now, what we can do is: we are going to output things, the same as we did before.0638

We are going to test if firstName is equal to null and if the lastName property is equal to null.0642

And if not, it is going to store, in the value of firstName and lastName, the values of those firstName and lastName properties, respectively.0646

And if not, it is going to return null.0653

Now, because, when you call this constructor, it is going to set these values for the firstName and lastName properties,0655

when this ternary operation occurs and these echo statements occur, 0662

it is going to output that firstName and lastName we provided to the constructor.0668

If we run this script as is, we can see that it outputs that firstName equals Joe and lastName equals Smith.0673

Now, in our previous version of Person, we had a default construction that didn't take any parameters0682

and just set the default values to the empty string.0687

In that example, if we wanted to set the firstName and lastName properties of that Person object,0692

we would have to say like "firstName='Joe'" and we would have to call it in a separate assignment statement.0700

So now, when we go and run this version of (actually, let's do a different name, 'Joe Jones,' so we can see there is a difference)...0720

and we go back to our last script, the noArgConstructor, we can see that now it outputs Joe and Jones.0731

But we had to go and use these two separate assignment statements.0738

What this new constructor that accepts parameters does is: it allows us to create a Person and set the names of some of its properties,0743

without having to call separate assignment statements; that is one of the nice things that you can use a constructor for.0754

And then, one of the key things with constructors is that, if a constructor does take, for example, two parameters0762

(our Person object, in this case--the constructor takes two parameters), you have to pass it all of those parameters.0770

So, let's say we leave out one of them, and we run our script.0777

We are going to get an error from PHP, saying there is a missing argument for our constructor method.0783

It is saying that you have to provide argument values for all of the parameters of a particular function.0798

Now, as mentioned, a key thing that a constructor does is set default values for properties.0812

In this case, our constructor requires two parameters; so, our firstName and lastName always get set, every time that constructor is called.0821

In our last example, where we didn't accept any parameters, this one causes problems if you don't properly initialize things.0829

Let's say we had a new property to this Person class called arr1, which is going to represent an array.0839

And let's say that, in our constructor, we don't initialize it.0849

We'll go ahead and initialize firstName and lastName, as before.0856

And when we go ahead and run this noArgConstructor script, it is going to run (let's get rid of these) fine, and it works as functions.0862

However, because users of our Person class will know that it contains an array as one of its properties, maybe they will try to access that array.0879

For example, maybe they will run a test that tests for a particular value in that array.0893

For example, they will call in the Person object; they will access that property, arr1.0900

And they are going to say, using the in_array function, for example, "Is the string 1 within that array property of the Person object?"0907

Now, because that hasn't been initialized, this is going to cause an error.0924

So, if we go ahead and try to load this now, it's going to say, "Warning: in_array() expects parameter 2 to be array."0928

This is an example of some of the problems that come up when you don't initialize the properties of your class.0935

The way you would handle this would be to go ahead, in our Person class, in the constructor,0943

which is the place to do this, and say arr1 equals empty array.0949

So now, it is definitely an array; it is an empty array, but at least it won't cause problems when other code tries to access it as an array.0956

Now, when we run our script, it is not going to throw any problems, because it is actually an array data type.0964

A couple of things to note: as you have seen in our web application example, a class is not required to have a constructor method.0974

We haven't actually had that, for example, in our Item and Department objects within our web application.0981

However, if it is provided, PHP will automatically run it for you.0988

As mentioned (to mention it again), it is good practice to make sure that all of an object's properties are initialized.0992

And you can do that in the constructor method.0998

And then, one thing to note, for those of you that have used other programming languages, is:1001

unlike other programming languages, in PHP, you can only have one constructor defined per class.1005

A lot of other languages allow what is known as constructor overloading, where you can have different constructors for an object that take different parameters.1009

And depending on how many parameters, for example, you put in parentheses when you are declaring an instance of an object,1017

the other programming languages, will call different constructors, based on how many parameters are provided.1033

So, you can maybe have two constructors: maybe one of them takes one parameter, and one of them takes two.1040

Well, on PHP, that is not allowed; so for those of you that are familiar with that in other languages, that is not something that you can do in PHP.1047

For the homework challenge, what I am going to have you do is update something that you did in our last homework, which is our HttpRequest class.1056

The first thing I am going to have you do is create a new property for the class called method.1065

And method is going to be an integer that can have a value of 0 or 1, to represent whether this HttpRequest is a GET request or a POST request.1070

If the value is 0, it is a GET request; if the value is 1, it is a POST request.1079

Then, what I want you to do is alter the getRequest method so that, when it outputs that first line of HttpRequest1086

(for example, GET /index.html, HTTP /1.1), it is going to test the value of this method property.1092

And if it is a 0, it is going to use the GET method; it is going to output GET /index.html.1101

If it is a 1, it is going to use the POST method; it is going to say POST /index.html.1105

Update the getRequest method.1111

Then, I want you to add a constructor (and that is what we are going to take from this lesson today) that takes two parameters.1114

The first one is going to be the uri property.1120

As you remember from our HttpRequest class that you were to design in the last homework, 1124

the HttpRequest object has a uri property that represents the URI for this HTTP request.1130

So, you are going to pass in a string; the constructor is going to take a string that is going to set the uri property.1139

It is also going to take an integer, a 0 or a 1, that is going to allow you to set the method property.1143

When we create this HttpRequest, we can set its method and its uri, all by calling the constructor.1149

Make sure, also, that your constructor initializes the headers property.1156

You are probably going to want to do it to an empty array, because headers, as you remember, is an array.1163

That is what we are using it as within our HttpRequest class.1168

And the constructor is a place where we initialize object variables, so we are going to give it the default value, typically, of an empty array.1175

So, make sure you do that for headers.1182

And then, I want you to go ahead and create an instance of this new updated HttpRequest class,1184

where you supply it both some random URI (like /index.html), and then a 1 that is going to set the method property to the POST method.1190

Go ahead and add a Host header to the object, using the addHeader method.1203

And then, call getRequest on that object, and output its output between pre tags.1208

And then, verify that your output has the format here.1214

If it is implemented correctly, you should see that POST is output as the method of this request, 1217

because we passed it a 1 when we created the instance; and also, that it has a Host header on it, as well.1224

And the value of that can be whatever you pass to it.1233

But the main portion for this lesson is about the POST.1235

Then, what I want you to do is alter the constructor so that, if a value is provided for method...1239

because it is a parameter required for that constructor, I can provide a method with a value that is a string 'A.'1245

Well, that is not a 0 or a 1, so that is not useful to us.1252

So, in the constructor, if the value provided for the method property is not a 0 or a 1, then it is going default1255

and set the value method equal to 1, which, in this case--the default would be the GET method.1264

So, this is an example of how you can also use your constructor to make sure that your objects start off in a well-known state.1270

You can perform some error checking; so, instead of being able to set...1277

all of your functions (for example) in your HttpRequest object are going to be expecting a 0 or a 1 as a value for method.1282

Well, by using the constructor to ensure that method only gets set to a 0 or a 1, 1290

you are going to make sure that those other functions are going to work as expected.1297

Then, to test out that this new constructor that tests method to make sure it is a valid value works,1302

go ahead and create another instance of the class, but this time providing the integer 5 as the method argument.1310

And then, verify that now, when you output the request using the getRequest method,1317

it actually has the GET method listed in the request.1322

And that is because your constructor should, by default, if a 0 or 1 is not provided, default method to 0, which corresponds to the GET method.1326

That ends today's lesson; thank you for watching look forward to seeing you next time.1335