PHP
  Home arrow PHP arrow Page 4 - Defining Public and Protected Methods with Member Visibility in PHP 5
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

Defining Public and Protected Methods with Member Visibility in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 2
    2008-06-11


    Table of Contents:
  • Defining Public and Protected Methods with Member Visibility in PHP 5
  • Calling methods of a class globally
  • Declaring and implementing protected methods within PHP 5 classes
  • Calling protected methods from a subclass

  • 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


    Defining Public and Protected Methods with Member Visibility in PHP 5 - Calling protected methods from a subclass
    ( Page 4 of 4 )


    Before you finish this article, I'd like to show you a final educational example to illustrate what occurs when the protected methods of the previous "DataSaver" class are accessed by one of its subclasses.

    To recreate this particular scenario, I'm going to create the mentioned subclass, as indicated below:


    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

    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

    protected function getFilePath(){

    return $this->filePath;

    }

    // get data via an accessor

    protected function getData(){

    return $this->data;

    }

    }


    // extends 'DataSaver' class

    class DataHandler extends DataSaver{

    // fetch data from target file

    public function fetch(){

    if(!$data=file_get_contents($this->filePath)){

    throw new Exception('Error reading data from target file.');

    }

    return $data;

    }

    // fetch all data

    public function getAllData(){

    return 'Target File: '.$this->getfilePath().' Data: '.$this->getData();

    }

    }


    I simply retrieved a basic subclass, called "DataHandler," from the pertinent "DataSaver" parent to expand its existing functionality. However, apart from grasping how the sub classing process functions, I'd like you to pay attention to a brand new method, named "getAllData()," that is defined by the child class.

    As you can see, this method returns the values of the respective $data and $filePath properties to client code by using two protected methods ("getFilePath()" and "getData()") implemented by the corresponding base class.

    In theory, it would be perfectly possible to call the "getAllData()" method without getting any fatal errors, since the pertinent protected methods are invoked from inside the child class. But in practice, would it be possible? Of course, this can be done!

    And to demonstrate the veracity of this concept, below I coded a short script that shows how the protected methods in question are seamlessly called via the  "getAllData()" method. Here's the corresponding code sample:


    try{

    // create new instance of 'DataHandler' class

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

    // save data to target file

    $dataHandler->save();

    // fetch data from target file

    echo $dataHandler->fetch();

    // call protected methods

    echo $dataHandler->getAllData();

     

    /* displays the following

    Target File: datafile.txt Data: This string of data will be saved to a target file!

    */

    }

    catch(Exception $e){

    echo $e->getMessage();

    exit();

    }


    Even though the above script looks pretty simplistic, it does demonstrate how two protected methods defined by a parent class can also be called from inside an eventual subclass. Of course, as with many other topics related to PHP 5 web development, the best way to acquire a solid background in working with protected methods is through practice.

    Final thoughts

    In this fourth chapter of the series, I provided you with an introductory guide on how to declare and implement public and protected methods within PHP 5 classes. As you saw, the topic is quite simple to grasp, so I guess you shouldn't have major problems mastering its basic concepts.

    In the next part, I'll be explaining the use of private methods in PHP 5. If you're interested in learning how to increase the level of restriction for the methods of your PHP 5 classes, then you simply can't miss this article!



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