Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
This chapter is from the book

Creating an Object

Using OOP is a two-step process. The first—defining a class—you just did when you wrote the HelloWorld class. The second step is to make use of that class by creating an object (or a class instance).

Going back to my User class analogy, an instance of this class may be for the user with a username of janedoe. The user’s attributes might be that username, a user ID of 2459, and an email address of jane@example.com. This is one instance of the User class. A second instance, john_doe, has that username, a user ID of 439, and an email address of john.doe@example.edu. These are separate objects derived from the same class. They are the same in general, but different in specificity.

Creating an object is remarkably easy in PHP once you’ve defined your class. It requires the keyword new:

$object = new ClassName();

Now the variable $object exists and is of type ClassName (instead of type string or array). More technically put, $object is an instance of ClassName.

To call the methods of the class, you use this syntax:

$object->methodName();

(The -> can be called the object operator.)

If a method takes arguments, you provide those within parentheses, as in any function call:

$object->methodName('value', 32, true);

To access an object’s properties, use

$object->propertyName;

Note that you would not use the property variable’s dollar sign, which is a common cause of parse errors:

$object->$propertyName; // Error!

(As you’ll also see in the next chapter, the ability to reference an object’s method or property in this manner depends upon the member’s visibility.)

Once you’ve finished with an object, you can delete it as you would any variable:

unset($object);

Simple enough! Let’s go ahead and quickly make use of the HelloWorld class.

To create an object:

  1. Create a new PHP document in your text editor or IDE, to be named hello_object.php, beginning with the standard HTML (Script 4.2):
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Hello, World!</title>
  <link rel="stylesheet"
href="style.css">
</head>
<body>
<?php # Script 4.2 - hello_object.php

The class definition file itself contains no HTML, as it’s not meant to be used on its own. This PHP page will include all of the code necessary to make a valid HTML page.

Script 4.2. In this page, PHP uses the defined class in order to say Hello, world! in several different languages.

1    <!doctype html>
2    <html lang="en">
3    <head>
4       <meta charset="utf-8">
5       <title>Hello, World!</title>
6       <link rel="stylesheet" href="style.css">
7    </head>
8    <body>
9    <?php # Script 4.2 - hello_object.php
10   /* This page uses the HelloWorld class.
11    * This page just says "Hello, world!".
12    */
13
14   // Include the class definition:
15   require('HelloWorld.php');
16
17   // Create the object:
18   $obj = new HelloWorld();
19
20   // Call the sayHello() method:
21   $obj->sayHello();
22
23   // Say hello in different languages:
24   $obj->sayHello('Italian');
25   $obj->sayHello('Dutch');
26   $obj->sayHello('French');
27
28   // Delete the object:
29   unset($obj);
30   ?>
31   </body>
32   </html>
  1. Include the class definition:

    require('HelloWorld.php');

    In order to create an instance of a class, the PHP script must have access to that class definition black_cicle-a.jpg. As the definition is stored in a separate file, that file must be included here. By using require() (as opposed to include()), the script will stop executing with a fatal error if the file could not be included (and there is no point in continuing without this file).

  2. Create the object:

    $obj = new HelloWorld();

    This one line of code is all there is to it! You can give the object variable any valid name you’d like, of course.

  3. Invoke the sayHello() method:

    $obj->sayHello();

    This line of code will call the say-Hello() method, which is part of the $obj object. Since the method is not being given any arguments, the greeting will be in the default language of English.

  4. Say hello in a few more languages:

    $obj->sayHello('Italian');
    $obj->sayHello('Dutch');
    $obj->sayHello('French');

    An object’s methods can be called multiple times, like any other function. Different arguments are provided to vary the result.

  5. Delete the object and complete the page:

    unset($obj);
    ?>
    </body>
    </html>

    You don’t technically have to delete the object—it will be deleted as soon as the script ends. Still, I think it’s better programming form to tidy up like this.

  6. Save the file as hello_object.php and place it in your Web directory, along with HelloWorld.php.

    You don’t have to place both documents in the same directory, but if they are stored separately, you will need to change the require() line accordingly.

  7. Test hello_object.php by viewing it in your Web browser black_cicle-b.jpg.
04fig02.jpg

black_cicle-b.jpg The resulting Web page (the examples will get better, I promise).

Note that you should run hello_ object.php, not HelloWorld.php, in your Web browser.

  • + Share This
  • 🔖 Save To Your Account