Programming Basics

  Home arrow Programming Basics arrow Object-Oriented PHP: Constructors and ...
PROGRAMMING BASICS

Object-Oriented PHP: Constructors and Destructors
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 3
    2010-05-19

    Table of Contents:
  • Object-Oriented PHP: Constructors and Destructors
  • Invoking Parent Constructors
  • Destructors
  • Static Class Members
  • Helper Functions
  • Autoloading Objects

  •  
     

    SEARCH CODEWALKERS

    Object-Oriented PHP: Constructors and Destructors


    (Page 1 of 6 )

    In this third part of a three-part series on the principles of object-oriented programming and PHP, you'll learn about constructors and destructors, static class members, and more, This article is excerpted from chapter six of the book Beginning PHP and PostgreSQL 8: From Novice to Professional, written by W. Jason Gilmore and Robert H. Treat (Apress; ISBN: 1590595475).

     Constructors and Destructors

    Often, you’ll want to execute a number of tasks when creating and destroying objects. For example, you might want to immediately assign several fields of a newly instantiated object. However, if you have to do so manually, you’ll almost certainly forget to execute all of the required tasks. Object-oriented programming goes a long way toward removing the possibility for such errors by offering special methods, called constructors and destructors, that automate the object creation and destruction processes.

    Constructors

    You often want to initialize certain fields and even trigger the execution of methods found when an object is newly instantiated. There’s nothing wrong with doing so immediately after instantiation, but it would be easier if this were done for you automatically. Such a mechanism exists in OOP, known as a constructor. Quite simply, a constructor is defined as a block of code that automatically executes at the time of object instantiation. OOP constructors offer a number of advantages:

    1. Constructors can accept parameters, which are assigned to specific object fields at creation time.
    2. Constructors can call class methods or other functions. 
       
    3. Class constructors can call on other constructors, including those from the class parent.

    This section reviews how all of these advantages work with PHP 5’s improved constructor functionality.


    Note  PHP 4 also offered class constructors, but it used a different, more cumbersome syntax than that used in version 5. Version 4 constructors were simply class methods of the same name as the class they represented. Such a convention made it tedious to rename a class. The new constructor-naming convention resolves these issues. For reasons of compatibility, however, if a class is found to not contain a constructor satisfying the new naming convention, that class will then be searched for a method bearing the same name as the class; if located, this method is considered the constructor.


    PHP recognizes constructors by the name __construct. The general syntax for constructor declaration follows:

    function __construct([argument1, argument2, ..., argumentN])
    {
       
    /* Class initialization code */
    }

    As an example, suppose you wanted to immediately populate certain book fields with information specific to a supplied ISBN. For example, you might want to know the title and author of the book, in addition to how many copies the library owns, and how many are presently available for loan. This code might look like this:

    <?php
       
    class book
       
    {
          
    private $title;
           private $isbn;
           private $copies;

           public function __construct($isbn)
           {
              $this->setIsbn($isbn);
              $this->getTitle();
              $this->getNumberCopies();
           }

           public function setIsbn($isbn)
           {
              $this->isbn = $isbn;
           }

           public function getTitle() {
              $this->title = "Beginning Python";
              print "Title: ".$this->title."<br />";
           }

           public function getNumberCopies() {
              $this->copies = "5";
              print "Number copies available: ".$this->copies."<br />";

           }
        }

        $book = new book("159059519X");
    ?>

    This results in:

    --------------------------------------------
    Title: Beginning Python
    Number copies available: 5
    --------------------------------------------

    Of course, a real-life implementation would likely involve somewhat more intelligent get methods (methods that query a database, for example), but the point is made. Instantiating the book object results in the automatic invocation of the constructor, which in turn calls thesetIsbn(),getTitle(), andgetNumberCopies()methods. If you know that such method should be called whenever a new object is instantiated, you’re far better off automating the calls via the constructor than attempting to manually call them yourself.

    Additionally, if you would like to make sure that these methods are called only via the constructor, you should set their scope toprivate, ensuring that they cannot be directly called by the object or by a subclass.

    More Programming Basics Articles
    More By Apress Publishing

    blog comments powered by Disqus

    PROGRAMMING BASICS ARTICLES

    - The Transliteration Operator in Perl
    - Perl String Processing Functions
    - Perl String Processing
    - Control Flow Constructs: Loops Conclusion
    - Loop Control Constructs
    - Control Flow Constructs: the For and Foreach...
    - Loops and Control Flow Constructs
    - Expression Modifiers for Perl Control Flow C...
    - Logical Operators and Control Flow Constructs
    - Comparing Strings with Control Flow Construc...
    - Perl Operators and Control Flow Constructs
    - Control Flow Constructs
    - More Time Manipulation with PHP
    - Validating and Manipulating Dates with PHP
    - Using the Date Constructor in PHP

    Developer Shed Affiliates

     



    © 2003-2014 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap