PHP
  Home arrow PHP arrow Page 4 - More on Private Methods with PHP 5 Mem...
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
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? 
PHP

More on Private Methods with PHP 5 Member Visibility
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 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:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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! 


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · This last article of the series covers some additional aspects concerning the use of...
     

       

    PHP ARTICLES

    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...
    - Working with the Email Class in Code Igniter





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
    Stay green...Green IT