Step 13:

Constructors

All objects can have a special built-in method called a ‘constructor’. Constructors allow you to initialise your object’s properties (translation: give your properties values,) when you instantiate (create) an object.

Note: If you create a __construct() function (it is your choice,) PHP will automatically call the __construct() method/function when you create an object from your class.

The ‘construct’ method starts with two underscores (__) and the word ‘construct’.

Note: When you declare a property with the ‘var’ keyword, it is considered ‘public’.

Step 16:

Restricting access to properties: part 2

When you declare a property as ‘private’, only the same class can access the property.

When a property is declared ‘protected’, only the same class and classes derived from that class can access the property – this has to do with inheritance …more on that later.

Properties declared as ‘public’ have no access restrictions, meaning anyone can access them.

To help you understand this (probably) foggy aspect of OOP, try out the following code and watch how PHP reacts. Tip: read the comments in the code for more information:

<?phpinclude("class_lib.php");?><?php$stefan=new person("Stefan Mischook");echo"Stefan's full name: ".$stefan->get_name();/*
Since $pinn_number was declared private, this line of code
will generate an error. Try it out!
*/echo"Tell me private stuff: ".$stefan->pinn_number;?>

Note: If you try to access a private property/variable outside of the class, you will get this:

Notes: Since the method get_pinn_number() is ‘private’, the only place you can use this method is in the same class – typically in another method. If you wanted to call/use this method directly in your PHP pages, you would need to declare it ‘public’.

Nerd Note: Again, it is important (as we go along,) that you actually try the code yourself. It makes a HUGE difference!