Working with Objects in PHP 5

Working with Objects in PHP 5Now we'll move to more advanced features of Object Oriented Programming, or OOP.

Objects and Their Properties

Objects have access to special variables called properties. You can declare them anywhere within the body of your class, but for the sake of clarity, you should define them at the top. A property can be a value, an array, or even another object:

class Item {

var $name = "item";
}

Notice that we declared our variable with the var keyword. In PHP 4, this was the only way to declare a property. We will look at some additional approaches that PHP 5 makes available later in the hour. If you are writing code that needs to be compatible with PHP 4, then you should use var .

Now any Item object that is created contains a property called $name with the value of "item" . You can access this property from outside the object and even change it:

class Item {

var $name = "item";

}

$obj1 = new Item();
$obj2 = new Item();
$obj1->name = "widget 5442";
print "$obj1->name<br />";
print "$obj2->name<br />";
// prints:
// widget 5442
// item

The -> operator allows you to access or change the properties of an object. Although $obj1 and $obj2 were born with the name of "item" , we have given $obj2 an individual identity by assigning the string "widget 5442" to its $name property, before using the -> operator once again to print each object's name property to the screen.

You can use objects to store information, but that makes them only a little more interesting than associative arrays. In the next section, we will look at object methods, and your objects can get a little more active.

Using Methods Contained within Objects

A method is a function defined within a class. Every object instantiated from the class has the method's functionality. In the next example, we will add a method to the Item class (line 5).

<?php
class Item {
var $name = "item";

function getName() {
return "item";
}
}

$item = new Item ();
print $item->getName ();
// outputs "item"
?>

As you can see, a method looks and behaves much like a normal function. A method is always defined within a class, however. You can call an object method using the -> operator, just as you can access any object property with the -> operator. Importantly, methods have access to the class's member variables. In the next example, we return the string "item" when asked for the Item object's name. Clearly, this isn't good practice: the method's return value should be a copy of the $name property and not a string literal. You've already seen how to access a property from outside an object, but how does an object refer to itself? Well, let's take a look...

<?php
class Item {
var $name = "item";

function getName () {
return $this->name;
}
}

$item = new Item ();
$item->name = "widget 5442";
print $item->getName ();
// outputs "widget 5442"
?>

A class uses the special variable $this to refer to the currently instantiated object, or it's "current self". You can think of it as a personal pronoun. Although you refer to an object by the handle you have assigned it to ( $item , for example), an object must refer to itself by means of the $this variable. Combining the $this pseudovariable and -> , you can access any property or method in a class from within the class itself.

Imagine that you want to allow some objects to have different $name property values than others. You could do this by manually resetting the $name property as you did earlier, or you could create a method to do it for you, as demonstrated by the next example.

<?php
class Item {
var $name = "item";

function setName( $n ) {
$this->name = $n;
}

function getName() {
return $this->name;
}
}

$item = new Item();
$item->setName("widget 5442");
print $item->getName ();
// outputs "widget 5442"
?>

The name property of the object begins as "item", but after the object's setName() method is called, it is changed to "widget 5442" . Notice how the object is capable of adjusting its own property. Notice also that you can pass arguments to the method in exactly the same way as you would to a normal function.

Object Constructors

In our previous example, we used a method, setName() , to amend the $name property. The initial value for the name property was hard-coded into the class:

var $name = "item";

If we expect the $name property to hold a different value for every instance of the Item class, we would do better to offer the client coder the chance to set the $name property when the object is initialized. We can use a special function called a constructor to set properties and perform any other preparatory work we require. A constructor is automatically called when the object is instantiated using the new keyword.

You can create constructors in two ways. Prior to PHP 5, the constructor was always a function that took the same name as the class that contained it. The following example adds a traditional constructor to the Item class. This code is still valid in PHP 5.

<?php
class Item {
var $name;

function Item( $name="item") {
$this->name = $name;
}

function setName( $n) {
$this->name = $n;
}

function getName () {
return $this->name;
}
}

$item = new Item("widget 5442");
print $item->getName ();
// outputs "widget 5442"
?>

The Item() constructor method is automatically called when we instantiate an Item object. We set up a default so that the string "item" is assigned to the parameter if we don't include an argument when we create our object.

PHP 5 introduces a new syntax for constructor methods. Instead of using the name of the class, you can use the special syntax __construct() . So we could converta portion of the previous example to use the new syntax by replacing Item() with ___construct() :

function __construct( $name="listing") { // .. }

This is not change for its own sake. We will encounter a good reason for using the new constructor syntax in future papers on OOP with PHP 5.

Important: The __construct() method was introduced with PHP 5. The method name does not have special significance in PHP 4, and the method is not called automatically. Therefore, it is not recommended to use the method in older versions of PHP.


Related Articles

  • Object Oriented Programming With PHP 4.1.x
    Object Oriented Programming provides raw power to PHP 4.1.x Part 1:Introduction First off, an object (also know as a class) is a very simple section of code that has a section of its own variables and functions. In a simple way an object is kind of like a program itself. Objects can be used fo...
  • An Introduction to ROR (Resources of a Resource)
    Why do people use ROR for describing the content, objects, and structure of websites in a generic fashion? Don
  • JavaScript Browser Detection
    Browser detection allows you to find out what browser your viewer is using, and then perform a script based on it - or just to send a friendly message to those with your favorite browser.
  • Basic Design Principles Part 2 Tone, Texture, Light, And Shade
    This specifically applies to drawings more than photography, but tone and texture are very important. Tone refers to shading of light and dark on an object and texture is the visual and tactile surface characteristics of an object.
  • What is SOAP?
    A detailed explanation of SOAP, the Simple Object Access Protocol; an industry standard that Microsofts .NET technology initiative is based on.
  • Logo Designs on the Go
    Logo sets up an identity and name for the business that aims to be remembered. It is something that a business really needs to have to instill in the customers a sense of belongingness and authenticity of business. Your business logo should contain new colors, casual and fun look and a uniquenes...
  • Some PHP Functions You Must Know
    PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML.
  • 4 Powerful Features of Javascript Programming Language
    In the community of web developers and surfers, Javascript is highly popular as client side scripting language for web browsers. Lets take a look at some of the features of this language.
  • A Simple Way to Beef up your PageRank
    Google is obviously, one of, if not THE biggest and most widely used search engine on the internet. What makes Googles search engine so amazing is their top-secret searching algorithm which of course searches through content on pages. Yes, pages, not SITES. Many newcomers to Search Engine Opti...
  • Designing Portfolio Section (Exclusive Tutorial)
    Dont worry about the content. Lets assume that you have already got something to show and were now going to arrange all this fast and correctly. For myself, I chose the sexiest image of a portfolio - the shape of a notebook. You are free to create and contrive for your own pleasure though:

Contact Web Design Outsource and get started today

Need Website Designing, Development, Redesigning, Maintenance and SEO services or help growing your company's web presence? Request a free Quote Now.