• PHP Tutorial

For many PHP programmers, object-oriented programming is a frightening concept, full of complicated syntax and other roadblocks. As detailed in my book, Pro PHP and jQuery, you'll learn the concepts behind object-oriented programming (OOP), a style of coding in which related actions are grouped into classes to aid in creating more-compact, effective code.

  • Advanced PHP
  • PHP Form Examples
  • PHP login Examples
  • PHP AJAX Examples
  • PHP XML Example
  • PHP Frame Works
  • PHP Design Patterns
  • PHP Function Reference
  • PHP Useful Resources
  • Selected Reading

We can imagine our universe made of different objects like sun, earth, moon etc. Similarly we can imagine our car made of different objects like wheel, steering, gear etc. Same way there is object oriented programming concepts which assume everything as an object and implement a software using different objects.

Object Oriented Concepts

Before we go in detail, lets define important terms related to Object Oriented Programming.

  • Class − This is a programmer-defined data type, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object.

  • Object − An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance.

  • Member Variable − These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. Gnat gpl 2009 for mac. These variables are called attribute of the object once an object is created.

  • Member function − These are the function defined inside a class and are used to access object data.

  • Inheritance − When a class is defined by inheriting existing function of a parent class then it is called inheritance. Here child class will inherit all or few member functions and variables of a parent class.

  • Parent class − A class that is inherited from by another class. This is also called a base class or super class.

  • Child Class − A class that inherits from another class. This is also called a subclass or derived class.

  • Polymorphism − This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it take different number of arguments and can do different task.

  • Overloading − a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation.

  • Data Abstraction − Any representation of data in which the implementation details are hidden (abstracted).

  • Encapsulation − refers to a concept where we encapsulate all the data and member functions together to form an object.

  • Constructor − refers to a special type of function which will be called automatically whenever there is an object formation from a class.

  • Destructor − refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope.

Defining PHP Classes

The general form for defining a new class in PHP is as follows −

Here is the description of each line −

  • The special form class, followed by the name of the class that you want to define.

  • A set of braces enclosing any number of variable declarations and function definitions.

  • Variable declarations start with the special form var, which is followed by a conventional $ variable name; they may also have an initial assignment to a constant value.

  • Function definitions look much like standalone PHP functions but are local to the class and will be used to set and access object data.

Example

Here is an example which defines a class of Books type −

The variable $this is a special variable and it refers to the same object ie. itself.

Creating Objects in PHP

Once you defined your class, then you can create as many objects as you like of that class type. Following is an example of how to create object using new operator.

Here we have created three objects and these objects are independent of each other and they will have their existence separately. Next we will see how to access member function and process member variables.

Calling Member Functions

After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only.

Following example shows how to set title and prices for the three books by calling member functions.

Now you call another member functions to get the values set by in above example −

This will produce the following result −

Constructor Functions

Constructor Functions are special type of functions which are called automatically whenever an object is created. So we take full advantage of this behaviour, by initializing many things through constructor functions.

PHP provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function.

Following example will create one constructor for Books class and it will initialize price and title for the book at the time of object creation.

Now we don't need to call set function separately to set price and title. We can initialize these two member variables at the time of object creation only. Check following example below −

This will produce the following result −

Destructor

Like a constructor function you can define a destructor function using function __destruct(). You can release all the resources with-in a destructor.

Inheritance

PHP class definitions can optionally inherit from a parent class definition by using the extends clause. The syntax is as follows −

The effect of inheritance is that the child class (or subclass or derived class) has the following characteristics −

  • Automatically has all the member variable declarations of the parent class.

  • Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent.

Following example inherit Books class and adds more functionality based on the requirement.

Now apart from inherited functions, class Novel keeps two additional member functions.

Function Overriding

Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class.

In the following example getPrice and getTitle functions are overridden to return some values.

Public Members

Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be accessed in three possible situations −

  • From outside the class in which it is declared

  • From within the class in which it is declared

  • From within another class that implements the class in which it is declared

Till now we have seen all members as public members. If you wish to limit the accessibility of the members of a class then you define class members as private or protected.

Private members

By designating a member private, you limit its accessibility to the class in which it is declared. The private member cannot be referred to from classes that inherit the class in which it is declared and cannot be accessed from outside the class.

A class member can be made private by using private keyword infront of the member.

When MyClass class is inherited by another class using extends, myPublicFunction() will be visible, as will $driver. The extending class will not have any awareness of or access to myPrivateFunction and $car, because they are declared private.

Protected members

A protected property or method is accessible in the class in which it is declared, as well as in classes that extend that class. Protected members are not available outside of those two kinds of classes. A class member can be made protected by using protected keyword in front of the member.

Here is different version of MyClass −

Interfaces

Interfaces are defined to provide a common function names to the implementers. Different implementors can implement those interfaces according to their requirements. You can say, interfaces are skeletons which are implemented by developers.

As of PHP5, it is possible to define an interface, like this −

Then, if another class implemented that interface, like this −

Constants

A constant is somewhat like a variable, in that it holds a value, but is really more like a function because a constant is immutable. Once you declare a constant, it does not change.

Declaring one constant is easy, as is done in this version of MyClass −

In this class, requiredMargin is a constant. It is declared with the keyword const, and under no circumstances can it be changed to anything other than 1.7. Note that the constant's name does not have a leading $, as variable names do.

Abstract Classes

An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class with the keyword abstract, like this −

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same visibility.

Note that function definitions inside an abstract class must also be preceded by the keyword abstract. It is not legal to have abstract function definitions inside a non-abstract class.

Static Keyword

Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can).

Try out following example −

Final Keyword

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

Following example results in Fatal error: Cannot override final method BaseClass::moreTesting()

Calling parent constructors

Instead of writing an entirely new constructor for the subclass, let's write it by calling the parent's constructor explicitly and then doing whatever is necessary in addition for instantiation of the subclass. Here's a simple example −

In this example, we have a parent class (Name), which has a two-argument constructor, and a subclass (NameSub1), which has a three-argument constructor. The constructor of NameSub1 functions by calling its parent constructor explicitly using the :: syntax (passing two of its arguments along) and then setting an additional field. Similarly, NameSub1 defines its non constructor toString() function in terms of the parent function that it overrides.

NOTE − A constructor can be defined with the same name as the name of a class. It is defined in above example.

Refactoring code is when you restructure existing code without changing its external behavior. Basically your aim is to make “bad” code better without changing the underlying functionality.There are plenty of guides out there on refactoring your code. However, I find many of them talk about the ideology of well written and structured code without actually showing you what it looks like to refactor your “bad” code into “good” code. They might talk about high-level concepts like readability, extensibility, maintainability, testability, reduced complexity etc., which are all valid aims of the refactoring process, but they often fail to show examples of what this looks like in reality.In this article I’m not going to talk about when you should refactor (personally I believe you should do it whenever you come across bad code), neither am I going to talk about why you should refactor (it reduces ). Rather I want to look at some common, practical principles you can apply when refactoring and give examples of what they look like with real code examples. For the purposes of this article I’ll be using PHP code (as WordPress is written in PHP) but these principles will apply to any programming language.

Don’t Repeat Yourself (DRY)Probably the most popular programming principle you’re likely to hear is “Don’t Repeat Yourself” (DRY). If you find yourself duplicating the same code a couple of times, then you should probably encapsulate the functionality in its own class or function and use said class or function to avoid repetition.

This means you only need to fix the code in one place when the inevitable bug arises months down the line.A good example of this is when two different but similar classes require some of the same functionality. Instead of duplicating the code across two different classes, you could create an which holds the common functionality and then make the other two classes extend the abstract class.For example. View the code on.This is just a simple example of how you can structure your code to avoid duplication. Splitting up Complex FunctionsAnother common programming problem that can lead to technical debt and hard-to-read code is complex functions or methods.“Programs must be written for people to read, and only incidentally for machines to execute.” – Harold AbelsonMaking your code easy for other people to read and understand is of utmost importance, so one way to deal with complex functions is to break them up into smaller more understandable (and testable) chunks.Here’s an example of a complex function. Don’t worry about understanding everything it does. Just notice how complex it looks to glance at.

View the code on.This is much easier to read and understand. It’s amazing the difference simply splitting up large, complex bits of code can make to a codebase.Another thing to note here is that you shouldn’t worry too much about having long, descriptive function names when splitting up complex functions like this.

Remember that the aim is human readability, so trying to be too concise with your function names can actually make your code harder to understand. For example: $this-getattinf( $postid );Is harder to understand than: $this-getattachments3info( $postid );Splitting Up Complex ConditionalsHave you ever seen big conditionals that look something like. View the code on.This makes your code far easier to understand for a future maintainer. As long as the conditional method is clearly named it should be easy to understand what it does without inspecting the actual method code. This practice is also known as.

Replacing Nested Conditionals with Guard ClausesAnother way to refactor complex conditionals is to use what are known as “guard clauses”. Guard clauses simply extract all conditionals that lead to calling an exception or immediate return of a value from the method and place it at the beginning of the method.

View the code on.Now even if the method gets more complex, it’s not going to be a maintenance headache down the road. Refactoring Loops and Conditionals Using Functional MethodsThis is a slightly more advanced type of refactoring that is used more heavily in functional programming languages and libraries (these kind of functions are used a lot in JavaScript land). You may have heard of functions like map and reduce and wondered what they are and how to use them. It turns out that these methods can dramatically improve the readability of your code.This example is inspired by on the subject (you should check out his upcoming book) and is based on using. However, I’ve adapted the example to work with standard PHP functions.Let’s look at two common scenarios and see how they can be improved using functional methods. Our example below fetches a bunch of $events from an API and calculates a score based on the event type. View the code on.Much better.

No loops or conditionals in sight. You could imagine how, if more complexity was required to find $types or calculate the $score down the line, it would be easy to refactor the map and reduce function calls into separate methods. This is now possible because we’ve already reduced the complexity down to a function. Further ReadingI’ve only just scraped the surface of refactoring in this article. There is plenty more I could have talked about, but hopefully this has given you a small insight into what it actually looks like to refactor your code.If you want to dive a bit deeper I recommend the.

It covers loads of topics and each one has an example so you can see exactly what the refactor looks like.Have you ever tried refactoring your code? Do you have any great refactoring tips you would like to share?

What do you think about functional methods? Let me know in the comments.