Quick explanation of PHP property types

If you have little object-oriented programming experience in PHP you might be a little confused by all the new terms in OOP programming compared to regular functional programming. Before we begin, remember the difference between the terms initialize and instantiate. This is common for all programming languages, not just PHP.

Initialize = assign a variable to a value (all variables/properties must have an initial value when created, even if the compiler does this automatically)
Instantiate = create a new instance of an object (which could be assigned to a variable).

In other words, you could initialize a variable and assign it to a class instantiation. Now, take a look at the example class below with some methods to describe how they work in practice:

class ITDB
private function __construct()
// Constructor runs when class is instantiated,
// like this: $test = new ITDB();

private function hello1()
// Only accessible in current class
protected function hello2()
// Only accessible in current class AND
// child classes which inherits this one
public function hello3()
// Accessible to all classes

// By declaring the method as "static" we can call the
// methods without having to instantiate the class first
static public function hello4()
// Accessible without having to instantiate a
// new ITDB() instance first

ITDB::hello1(); // Will not work because method is private

$sayhi = new ITDB(); // Instantiate class, assign to $sayhi
$sayhi->hello1(); // Will not work, hello1() is still private
$sayhi->hello3() // This is valid, hello3() is a public method

ITDB::hello4(); // Also valid, hello4() is a public static method

Let me know in the comments if you have any questions regarding this 🙂

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *