OOP PHP Lesson 1 – First Class

OOP PHP Lesson 1 – First Class

In first lesson of Object Oriented Programming I use very simple example of a class. This example is not political correct approach to object oriented programming, but just something to get you started. You will need two files: Customer.php and file which will be executed, with the content as written below:

$a_customer = new Customer(); //object creation, class instance of Customer
$a_customer->name='John'; //a customer gets name
$a_customer->hello(); // customer John says 'hello!'

Content for Customer.php file, where definition of Customer class is stored:


class Customer { //class name

public $name; //class property

public function hello() //class function
echo 'customer '.$this->name.' says: Hello!';
} //end of class definition


And, now, some explanation. The example uses two files: class definition file and main program file. Class could be explicitly defined in main program file as well, however sometimes we can have many classes, so to make everything more clear and easier for maintenance it is better to use separate files for classes definition, preferably with names exactly like class names.

Class definition file: class definition starts with keyword class and class name followed by opening curly bracket. In our example we use only one property $name and some simple method hello(). Access specifiers are set as public for both property and method.

In main file a Customer object is created (keyword new) and after that $a_customer gets name, and can say ‘hello!’ thanks to hello() method. $a_customer is instance of Customer class, and it is object, but in some way it is a kind of abstract variable – it can have a property (for instance name) like “standard” variable but as well it can do something.

The keyword this used in class method means, that we access some internal class property – in our example we access name.