Login

Defining Public and Protected Methods with Member Visibility in PHP 5

In the previous articles of this series, I explained how to work with public and protected class properties. So now it’s time to demonstrate how to specify these same levels of visibility in the respective methods of a class. Sounds pretty interesting, right?

As an enthusiastic PHP programmer, you should be aware of how useful it can be to protect the data members of your classes from unwanted access. Fortunately, when working specifically with PHP 5, setting different levels of restriction for the methods and properties of a specific class is a process reduced to specifying the appropriate keywords (i.e. whether they’re going to be public, protected, or private).

However, if you’re just starting to explore the huge terrain of object-based programming in PHP 5, then you’re probably looking for a comprehensive guide on how to use the member visibility feature incorporated into this language’s object model. In that case, there’s good news for you. In this group of articles you’ll learn all that you need to begin working with public, protected, and private class members in PHP 5.

Now that you know what will be treated in this fourth chapter of the series, it’s time to learn how to declare and implement public and protected methods with PHP 5 classes.

Of course, as always I’m going to address this useful topic by using a hands-on approach, which means that there’s a bunch of code samples ahead, waiting patiently for you. So, don’t waste more time and start reading this article now!

{mospagebreak title=Calling methods of a class globally}

Working with public class methods is an extremely simple process that can be grasped in a few minutes, even by inexperienced developers. Naturally, if you’ve used classes in PHP 4, then you should know that all the methods you define are public by default, since there’s no way to prevent them from being accessed globally.

However, as you may have noticed, it’s possible to use the “public” keyword to specify the visibility of a method in PHP 5. What’s more, if no visibility is assigned to a method, then it will be declared public also by default.

Let me stop discussing theory for a moment and show you a practical example, where you’ll learn how to declare and implement a few public methods. To do this, I’m going to use the familiar “DataSaver” class that you saw in the previous articles of the series. The signature is listed below:

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, all of the methods incorporated into the above class are declared public, which means that they can be called directly from outside the class in question. To understand this concept, look at the following script, which shows how to invoke some methods of the sample “DataSaver” class in the global scope:

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 public 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

Target file is the following : datafile.txt

Data for being saved to target file is the following : This string of data will be saved to a target file!

*/

}

catch(Exception $e){

echo $e->getMessage();

exit();

}

So far, there’s nothing unexpected. As you can see, because the “save(),” “getFilePath(),” and “getData()” methods of the above sample class have been declared public, they can be invoked directly from outside the mentioned class and the PHP interpreter won’t trigger any fatal errors.

Using public methods with PHP 5 is a no-brainer process, but even so, you should be very careful when declaring the visibility of methods that make up your own classes, particularly if you don’t want them to be accessed in the global context.

Well, assuming that you grasped how to work with public class methods, it’s time to move forward and continue with this educational journey. Therefore, in the course of the following section, I’m going to utilize the same data saving class that you saw before in order to explain how to declare and implement protected methods.

To learn the complete details on this useful topic, please go ahead and read the next few lines. They’re only one click away.

In accordance with the concepts that I expressed in the prior section, it would be pretty helpful to utilize the same data saving class that I created earlier to demonstrate how to declare and implement protected methods. Based on this simple schema, the next step will consist of listing the complete signature of the mentioned class, which now includes a couple of protected methods.

That being said, here’s how this sample class looks:

// define ‘DataSaver’ class (methods are defined protected)

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;

}

}

This time, the sample “DataSaver” class now contains two accessors, called “getData” and “getFilePath()” respectively, that have been declared protected. Essentially, this condition means that they can only be accessed within the originating class and within all of its eventual subclasses.

To demonstrate the veracity of this concept, below I coded yet another basic example to help you grasp the logic that stands behind using a pair of protected methods with the previous data saving class. Here’s the corresponding code sample:

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

As you can see, the PHP interpreter will trigger a fatal error each time a protected method of the “DataSaver” class is called globally. This demonstrates how useful a protected method can be when it comes to preventing it from being called outside a specific class.

Well, I should assume that you understand how to declare and implement a couple of protected methods within a primitive PHP 5 class. Thus, based on this assumption, in the following section, I’m going to show what happens when a protected method defined in a parent class is directly invoked by a subclass. Sounds quite interesting, right?

However, to see the complete details, you’ll have to click on the link below and keep reading.

{mospagebreak title=Calling protected methods from a subclass}

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:

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!