PHP
  Home arrow PHP arrow Page 4 - More on Private Methods with PHP 5 Member Visibility
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

More on Private Methods with PHP 5 Member Visibility
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 2
    2008-06-25


    Table of Contents:
  • More on Private Methods with PHP 5 Member Visibility
  • Reintroducing a previous hands-on example
  • Calling a private method from a subclass
  • Another way to protect class methods: the final keyword

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    More on Private Methods with PHP 5 Member Visibility - Another way to protect class methods: the final keyword
    ( Page 4 of 4 )

    Even though it’s not very popular with programmers, PHP 5 supports the use of the “final” keyword, which can be applied to a number of methods of a given class to prevent them from being overridden by any other subclass. Naturally, this keyword is an effective mechanism that can be used to protect one or more methods, but as I said before, isn’t widely utilized by developers nowadays.

    Despite its lack of popularity, you may want to see how the “final” keyword can be used in a concrete case. Below I redefined the same “Datasaver” class that I used in the previous section, and it now includes a final version of its “save()” method that can’t be overridden by any child class.

    That being explained, the brand new signature of the mentioned class looks like this:


    // define 'DataSaver' class (uses the 'final' keyword)


    class DataSaver{

    protected $filePath;

    protected $data;

    public function __construct($data,$filePath){

    if(!$data||strlen($data)>1024){

    throw new Exception('Invalid data for being saved to target file.');

    }

    if(!file_exists($filePath)){

    throw new Exception('Invalid target file.');

    }

    $this->data=$data;

    $this->filePath=$filePath;

    }

    // save data to target file

    final public function save(){

    if(!$fp=fopen($this->filePath,'w')){

    throw new Exception('Error opening target file.');

    }

    if(!fwrite($fp,$this->data)){

    throw new Exception('Error writing data to target file.');

    }

    fclose($fp);

    }

    // get target file via an accessor

    private function getFilePath(){

    return $this->filePath;

    }

    // get data via an accessor

    private function getData(){

    return $this->data;

    }

    }


    Pretty simple, right? As you can see, the “save()” method included in the above “Datasaver” class is preceded by the “final” keyword, meaning that the method in question can only be used “as is” by all of the eventual subclasses.

    To demonstrate this concept more clearly, I’m going to derive a child class from the pertinent “DataSaver.” This is indicated below:


    // extends 'DataSaver' class


    class DataHandler extends DataSaver{

    // try to override method in the parent

    public function save(){

    session_start();

    $_SESSION['data']=$this->data;

    }

    }


    As you can see, at this point I built a basic subclass that overrides the implementation of the “save()” method declared by the corresponding parent. However, this process simply won’t work because of the application of the “final” keyword, which is something that can be seen in the following script:


    try{

    // create new instance of 'DataHandler' class

    $dataHandler=new DataHandler('This string of data will be saved to a target file!','datafile.txt');

    // try to save data to target file

    $dataHandler->save();

    /* displays the following

    Fatal error: Cannot override final method DataSaver::save() in path/to/file/

    */

    }

    catch(Exception $e){

    echo $e->getMessage();

    exit();

    }


    Since the respective “save()” method has been declared “final,” it can’t be overridden by a subclass. So in the above script, the PHP interpreter triggers a fatal error notifying the user about this condition.

    As is usual with many of my articles on PHP web development, I encourage you to use all of the code samples included in this article so you can extend your existing skills in using member visibility in PHP 5.

    Final thoughts

    It’s hard to believe, but we’ve come to the end of this series. Overall, the experience has been instructive, since hopefully you now have a more solid background in declaring and implementing public, protected, and private class members when developing object-based applications with PHP 5.

    See you in the next tutorial on PHP development! 



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek