Utilizing Private Methods with PHP 5 and Member Visibility

Welcome to the fifth chapter of the series, “Protecting the data of PHP 5 classes with member visibility.” Comprised of six parts, this series teaches you how to define the levels of visibility that properties and methods of a specific class will have when developing PHP5-controlled applications. This article will show you how to declare methods and properties private.

The improved object model incorporated by PHP 5 provides programmers with the capacity to set up three different levels of access to the data members of classes. This implies that it’s very easy to specify whether the properties and methods of a given class will be public, protected, or private.

However, if you’re looking for an approachable guide that walks you through the basic concepts that surround the implementation of member visibility in PHP 5, then look no further because you’ve come to the right place.

Of course, when it comes to specifying how visible a certain class property or method will be, you know that PHP 5 permits you to work with three distinct levels of access, called “public,” “protected,” and “private” respectively. The preceding articles of the series were focused specifically on explaining how to assign the first two grades of visibility to the properties and methods of a rudimentary data saving class.

Hopefully, after playing around with the code samples included in the aforementioned tutorials, you’re adequately armed with the required background to start using public and protected data members within your own PHP 5 classes. As you may have noticed, however, I’ve not taught you how to define private methods yet, which is something that can definitely be very useful if you want to restrict the access to your classes from the outside more severely.

Therefore, in this fifth episode of this series, I’ll be explaining how to declare and implement private methods inside of a sample PHP class. This way you can begin incorporating this feature into your own object-oriented applications.

Now, let’s continue this educational journey about using member visibility with PHP 5. Let’s go!

{mospagebreak title=Working with protected methods in PHP 5-controlled environments}

Before I start teaching you how to define and implement private class methods in PHP 5, let me spend a brief moment refreshing some important concepts that were deployed in the last article of this series. I demonstrated how to create a trivial class that used a couple of methods, which were declared protected.

As you’ll surely recall, protected methods are preceded by the “protected” PHP keyword and can only be called from inside the originating class, or from inside the eventual subclasses. But, as always, this concept will be better grasped if you look at the following example, which shows what happens when a protected method defined within a sample class is called in the global scope.

Here’s the pertinent code sample:


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

protected function getFilePath(){

return $this->filePath;

}

// get data via an accessor

protected function getData(){

return $this->data;

}

}


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();

// call protected methods

echo ‘Target file is the following : ‘.$dataSaver->getfilePath().’<br />’;

echo ‘Data for being saved to target file is the following : ‘.$dataSaver->getData();

 

/* displays the following

Fatal error: Call to protected method DataSaver::getfilePath() from context ” in path/to/file/

*/

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


As you can see, the above hands-on example is a no-brainer. In this particular case, I used the familiar “DataSaver” class that you learned in previous tutorials in order to demonstrate how the PHP interpreter reacts when the protected methods of the class in question are called from outside of it. It triggers a fatal error.

Well, after examining the previous code sample, don’t you feel a bit more relaxed? You should, because at this point you’ve been familiarized with using a couple of protected methods within a basic data saving class.

Considering this promising scenario, it’s time to jump forward and continue learning more useful things concerning the utilization of member visibility with PHP 5. Therefore, as I stated in the introduction, in the course of the following section, I’m going to teach you how to use the same sample class listed previously, but this time to declare and implement private methods.

Are you curious about how this will be done? Don’t hesitate to read the next few lines. I’ll be there, waiting for you.

{mospagebreak title=Working with private data members}

If you found it easy to learn how to declare and implement protected methods using the “DataSaver” class, then I’m pretty sure that there will be a big smile on your face when I teach you how to work with private ones!

Well, I possibly got caught in the moment, but trust me, defining private methods in PHP 5 is a really simple process that only requires preceding the method that you wish to declare private with the “private” keyword. It’s simple and intuitive, isn’t it?

Besides, it’s important to say that any method defined as private can only be called from inside the originating class. Period. In this case, it can’t be accessed by any subclass, which restricts a method even more from unwanted calls.

Even so, the previous explanation would be rather incomplete if I didn’t show you an example of how useful a private method can be in concrete situations. So, once more I’m going to appeal to the sample “DataSaver” class to show you how to declare and implement a pair of private methods.

This being said, take a look at the code sample below, which includes the modified signature of this sample class and shows how the PHP engine throws a fatal error when one of these methods is called in the global scope:


// define ‘DataSaver’ class (methods 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

private function getFilePath(){

return $this->filePath;

}

// get data via an accessor

private function getData(){

return $this->data;

}

}


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();

// call private methods

echo ‘Target file is the following : ‘.$dataSaver->getFilePath().’<br />’;

echo ‘Data for being saved to target files is the following : ‘.$dataSaver->getData();

 

/* displays the following

Fatal error: Call to private method DataSaver::getFilePath() from context ” in path/to/file/

*/

 

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


Didn’t I tell you that using private methods with the above data saving class was going to be a straightforward process? And certainly, I was correct, since the previous example shows you very clearly how the PHP interpreter fires up a fatal error when a private method is directly called from outside the class in question.

With the previous example at your disposal, you can hopefully learn the basics of defining and implementing private methods within a basic PHP 5 class. So, what’s the next step to take from here? Well, it’s probable that you’re wondering how a private method can be called in the global scope without getting a fatal error.

In practical terms, this isn’t possible. However, there’s something that can be done to skip over this restriction, and it consists of simply using a public method to access a private one. Indeed, this idea may sound confusing, but it can be used to expand your recently-acquired background in working with private methods.

Thus, in the section to come, I’m going to set up a final example for you that will recreate this particular situation.

Please, click on the link below and keep reading.

{mospagebreak title=Accessing private methods with a public one}

As I said in the course of the previous section, the last thing that I’m going to teach you with reference to using private methods in PHP 5 will consist of demonstrating how these can be accessed from outside the originating class by way of a public method.

Given that, first I’m going to modify the signature of the sample “DataSaver” class that you learned earlier, and code a brand new method, called “getAllData(),” which will come in handy for accessing the pair of private methods defined previously.

Based on this idea, here’s the modified definition of the pertinent “DataSaver” class:


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

private function getFilePath(){

return $this->filePath;

}

// get data via an accessor

private function getData(){

return $this->data;

}

// get all data

public function getAllData(){

return ‘Target File : ‘.$this->getFilePath().’ Data : ‘.$this->getData();

}

}


As you can see, the above “DataSaver” class now implements an additional public “getAllData()” method, which is responsible for calling the private “getFilePath()” and “getData()” methods respectively. Based on the implementation of the mentioned “getAllData(),” it’s pretty easy to demonstrate how a couple of private methods can be accessed by a public one.

The below script recreates this specific situation for you. Here it is:


try{

// create new instance of ‘DataHandler’ class

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

// save data to target file

$dataSaver->save();

// call private methods via a public one

echo $dataSaver->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();

}


That was quite easy to grasp, wasn’t it? As you can see, by way of a simple workaround, like the above “getAllData()” public method, it’s perfectly possible to call the private “getFilePath()” and “getData()” methods respectively, without getting any fatal errors from the PHP interpreter.

As usual with many of my articles on PHP development, I suggest you practice using the code samples developed in this tutorial, so you can get more experience in working with private methods in PHP 5.

Final thoughts

In this fifth installment of the series, I provided you with a quick overview of how to declare and implement private methods within a PHP 5 class. As you learned before, this process is actually quite simple to tackle and only requires preceding the method that you want to declare private with the “private” keyword. That’s all you need!

In the final article of the series, I’ll be teaching you a few additional things concerning the use of private methods in PHP 5, such as creating an additional example that will help you understand what happens when a private method is called from within a subclass. In addition, I’ll be showing you how to utilize the “final” PHP 5 keyword, which can be helpful for protecting the data members of your classes from undesired access.

Now that you’ve been warned of the topics that will be discussed in the last article of this series, you won’t want to miss it!

Google+ Comments

Google+ Comments