How to Use PHP to Return the Date in JSON Format
PHP, MySQL, JavaScript & HTML5 All-in-One For Dummies Cheat Sheet
How to Query with the mysql Client

How to Create a PHP Class

The heart of the object-oriented programming is the class. The example shown here creates a Page class, which is part of a larger templating system built in the book. The full Page class includes various methods and properties that are used to build each page.

For this exercise, you'll create the beginnings of the class containing a few of the properties that are required in order to make an HTML web page.

Follow these steps for this exercise:

  1. Open your text editor and create a new empty file.

    image0.jpg
  2. Place the following PHP code in the file:

    <?php
     
    class Page
    {
     
        public $type = "default";
        public $title = "My Web Site";
        public $titleExtra = "";
     
    }   //end Page class
     
    ?>
  3. Save the file as classPage.php in your document root.

    image1.jpg

    With the Page class created, it can be instantiated. Because the three properties are public, they can be accessed and changed from the instantiating program. PHP can also create protected and private properties, each with their own set of access and modification rules.

This exercise showed how simple it is to create a class in PHP. The next step for the Page class is to add methods and additional properties as needed in order to create a full-fledged template system in PHP.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
How to Create an HTML Table
How to Set Local Time with PHP
How to Use JavaScript's GetElementById to Access a Specific Element
Advertisement

Inside Dummies.com