PHP
  Home arrow PHP arrow Page 4 - Working with Private Properties to Protect PHP 5 Class Data
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

Working with Private Properties to Protect PHP 5 Class Data
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 5
    2008-05-28


    Table of Contents:
  • Working with Private Properties to Protect PHP 5 Class Data
  • A review of public and protected class properties in PHP 5
  • Extending the use of protected class properties: working with a subclass
  • Defining private class properties

  • 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


    Working with Private Properties to Protect PHP 5 Class Data - Defining private class properties
    ( Page 4 of 4 )

    If you found working with public and protected properties of a given PHP 5 class easy, then it’s quite probable that you'll feel the same way when it comes to using private data members. By definition, any class property declared private can only be accessed from inside the originating class. That’s all.

    However, even though the above definition is very intuitive, it’s necessary to complement it adequately with a practical example. With that idea in mind, in the next few lines, I’m going to list the signature of the same “DataSaver” class that you saw earlier, but this time, its respective properties will be declared private.

    The brand new definition of this sample class looks like this:


    // define 'DataSaver' class (properties are defined private)


    class DataSaver{

    private $filePath;

    private $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

    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

    public function getFilePath(){

    return $this->filePath;

    }

    // get data via an accessor

    public function getData(){

    return $this->data;

    }

    }


    As you can see, the signature of the above “DataSaver” class remains practically the same, with the exception of the level of visibility assigned to its respective $data and $filePath properties, since they’ve been declared private.

    Obviously, this implies that the properties in question can only be accessed from inside the originating class, and any attempt to retrieve them from a different scope will result in a fatal error being triggered by the PHP interpreter.

    This condition is clearly reflected by the following hands-on example:


    try{

    // create new instance of 'DataSaver' class

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

    // save data to target file

    $dataSaver->save();

    // try to print value of private properties

    echo 'Target file is the following : '.$dataSaver->filePath.'<br />';

    echo 'Data for being saved to target file is the following : '.$dataSaver->data;

     

    /* displays the following

    Cannot access private property DataSaver::$filePath in path/to/file/

    */

    }

    catch(Exception $e){

    echo $e->getMessage();

    exit();

    }


    In the previous example, the private $data and $filePath properties are erroneously accessed from the global scope, which naturally made the PHP engine fire up a fatal error, as indicated above.

    With this final example, I'll assume that you’re already armed with the required background to understand how to declare the level of visibility for the properties defined by a specific PHP 5 class. However, you can use all of the code samples included here to improve your existing skills in this crucial topic.

    Final thoughts

    Throughout this second part of the series, I provided you with an introductory guide to using private class properties in PHP 5. Nonetheless, there are some additional aspects of this subject that need to be explored in more detail, such as accessing private data members by way of subclasses and accessors.

    But all of these interesting topics will be covered in the next part, so you don’t have any excuse to miss it!



     
     
    >>> 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 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek