Home arrow PHP arrow Page 4 - More on Private Methods with PHP 5 Member Visibility

Another way to protect class methods: the final keyword - PHP

Welcome to the final chapter of the series, “Protecting the data of PHP 5 classes with member visibility.” Complemented by copious illustrative examples, this article series guides you through learning the key concepts regarding the use of public, protected, and private data members within PHP 5 classes. This way you can start defining the visibility of the properties and methods of your own classes in a very short time.

TABLE OF CONTENTS:
  1. More on Private Methods with PHP 5 Member Visibility
  2. Reintroducing a previous hands-on example
  3. Calling a private method from a subclass
  4. Another way to protect class methods: the final keyword
By: Alejandro Gervasio
Rating: starstarstarstarstar / 2
June 25, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: