OOP - Using classes and objects
Posted under » PHP » OOP on 13 March 2009
As implied by the name, the central concept of OOP is the object. At a practical level, an object is simply a data structure comprised of functions and variables local to each object. The class from which the object is created defines what an object can do. An application can create many objects based on a single class definition. In OOP jargon, an object is an instance of a class, and the act of creating an object from a class is called instantiation.
The fundamental building block of all object-oriented code is called a class. This is simply a collection of related variables and functions, all wrapped up in a pair of curly braces and labeled with the name of the class. A class is the code that defines the functions and variables an object created from the class will have. The class definitions can be thought of as templates from which objects are created.
Objects properties
PHP has two kinds of scope; local and global. With objects, you get a third kind of scope, which is the objects properties. A major difference from procedural programming is that the properties and methods of an object can be declared protected or private. You can think of it as a kind of extended local variable. In general, global variables are bad practise, because of the (implicit) dependencies they introduce. Object properties doesn't have these problems, and this is one of the key benefits of object oriented programming.
Instance of a class
To use the variables and functions defined by a class, you create an instance of the class, which is referred to as an object. This creates an object called $val.
$val = new Pos_Validator();
This ability to hide from view the inner workings of a class is one of the three most important characteristics of OOP, namely:
However, building classes takes time and effort, so OOP isn't necessarily the best approach for simple, one-off tasks. Unless you know the code is going to be reused in other projects, it can feel like building a steam hammer to crack open a hazelnut.
Page 1 : OOP Introduction
Page 3 : Implementing a Simple Class in PHP
Page 4 : $this variable in OOP
