Protecting PHP 5 Class Data with Member Visibility

If you ever have the chance to gather a group of PHP programmers in a big room and ask them whether they find it hard to build classes with PHP, the invariable answer would probably be a resounding "No!" And admittedly, they’d be absolutely right, since PHP allows you to work with classes, methods, and properties in a pretty straightforward way. But there’s more to programming with classes, as this article series will explain.

As soon as a PHP developer masters the basic principles of object-oriented programming, s/he is faced with a challenging barrier of concepts that at first sight, might sound intimidating even to the bravest programmer: composition and aggregation, polymorphism and inheritance, object factories and singletons, and the list goes on and on. How can all these things be properly digested?

Well, in all these cases, an adequate balance between the corresponding theory and thorough practice can be the correct way to tackle the different facets that compose the so-called object-oriented paradigm, even though this learning process can take a long time.

The previous concept can also be applied successfully when it comes to defining the visibility of properties and methods in PHP classes. As you possibly know, aside from declaring a certain number of properties and implementing concrete methods within a given PHP class, it’s also possible (and highly recommended) to specify if they’ll be available globally, or restricted to the scope of the class itself and its eventual subclasses.

Using the jargon of object-oriented programming, this capacity is widely known as member visibility. This capacity allows PHP programmers to establish whether the set of methods and properties of a specific class will be public, protected, or private. This easily permits you to set different levels of “protection” for certain data members.

In plain terms, it isn’t possible to specify the grade of visibility that a member of a class will have in PHP 4, but similar results can be achieved with a bit of willpower. On the other hand, the object model of PHP 5 incorporates the “public,” “protected,” and “private” keywords, which can be used to indicate the visibility of methods and properties declared by a class.

Having briefly introduced the concepts that surround the implementation of “member visibility” in PHP 5, in this group of articles I’ll be taking a closer look at this fundamental topic, so you can learn by way of copious hands-on examples how to permit and restrict the access to the data of your PHP 5 classes.

Ready to begin this educational journey? Let’s get started!

{mospagebreak title=Making the properties of a class available in the global scope}

In order to explain how to work with the member visibility feature in PHP 5, I’m going to start building a basic class that will be tasked with saving an inputted string of data to a specified text file. The complete signature of this sample class is listed below, so take the time to examine it, please:


// define ‘DataSaver’ class (saves a string of data to a target file and their properties are defined public)


class DataSaver{

public $filePath;

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

}

}


The above “DataSaver” class isn’t going to change your life as a PHP developer, but it does demonstrate how to declare its two properties, called "$data” and “$filePath” as public members. This means that they can be freely accessed in the global scope.

However, to clarify this concept, in the next few lines, I’ve coded a simple script that first uses the previous class to save a trivial string to a determined text file, and then prints the pertinent values of the aforementioned properties on screen.

The corresponding code sample looks like this:


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

// print value of public 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

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

}


Since the pair of class properties have been declared public using the “public” keyword, they can be accessed directly from outside the originating class, as illustrated clearly by the previous hands-on example. In this particular case, the values assigned to these basic properties are echoed to the browser without any kind of restrictions because they’re available in the global scope. Are you starting to grasp how to declare a couple of public properties within a PHP 5 class? I guess you are!

All right, now that you understand how to work with properties of class that have been declared public, it’s time to see how to switch their visibility to “protected.” This implies that they can’t be accessed in the global scope. They are only visible from inside the originating class and also from all their eventual subclasses.

But actually, I’m getting ahead of myself, since this topic will be discussed in detail in the following section. Therefore, click on the link below and keep reading.

{mospagebreak title=Restricting the access to class properties}

Throughout the course of the previous section, I showed you how to declare a couple of public properties within a sample class in order to make them globally accessible. Assuming that you grasped how to achieve this, the next thing that I’m going to teach you will be how to build the same class, but this time I will define the respective properties as protected data members.

The signature of the pertinent “DataSaver” class will look like this:


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


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

public function getFilePath(){

return $this->filePath;

}

// get data via an accessor

public function getData(){

return $this->data;

}

}


Obviously, the definition of the above “DataSaver” class is nearly identical to the one that you learned in the previous section, except now the respective “$data” and “$filePath” properties have been declared protected by preceding them with the “protected” keyword. But what does this mean in simple terms?

Well, by definition, any data member defined as “protected” within a PHP 5 class can only be accessed from inside the originating class, and from inside all the eventual subclasses. This implies that they’re no longer globally available.

Of course, this concept will be better understood by example. So, below I set up another code sample that demonstrates how the PHP interpreter triggers a fatal error when the protected class properties are wrongfully accessed 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();

// print value of protected properties

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

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

 

/* displays the following fatal error with the first property

Fatal error: Cannot access protected property DataSaver::$filePath in path/to/file/

*/

/* displays the following fatal error with the second property

Fatal error: Cannot access protected property DataSaver::$data in path/to/file/

*/

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


Pretty simple to grasp, right? As you can see in the above example, the PHP 5 engine will fire up a fatal error each time a protected property is accessed from outside the originating class. This implements an effective restriction mechanism that can be applied to both properties and methods of a given class.

However, as I explained before, the properties in question can be accessed without any restrictions from inside the originating class. Therefore, in the last section of this tutorial I’m going to show you yet another practical example where this condition will be recreated for you.

To see how this final example will be developed, please click on the link below and keep reading.

{mospagebreak title=Accessing protected properties using class accessors}

In consonance with the concepts that I expressed in the section that you just read, the last example that I’m going to provide in this tutorial is aimed at demonstrating how the protected properties of the “DataSaver” class, which was created earlier, can be accessed from inside the class in question.

How will this be done? It’s very simple really, since, as you may have noticed, this sample class has a couple of access methods (also called accessors), named “getData()” and “getFilePath()” respectively. They can be used to retrieve the values of the protected properties from inside the class.

But to clarity things a bit more, I’m going to list the complete definition of the pertinent “DataSaver” class, to remind you of how these access methods look. Here it is:


// define ‘DataSaver’ class (properties are defined protected but are accessed by the accessors)


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

public function getFilePath(){

return $this->filePath;

}

// get data via an accessor

public function getData(){

return $this->data;

}

}


Now that you know how the access methods of the above “DataSaver” class have been implemented, please pay close attention to the following example, which shows how to output the values of the respective protected properties via the previously mentioned methods:


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

// print value of protected properties

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

}


Now the protected properties that belong to the pertinent data saving class are accessed from inside the class scope via the respective “getData()” and “getFilePath()” methods. This demonstrates how to retrieve their corresponding values within the class in question.

At this point you’ll have to agree with me that working with protected class properties in PHP 5 is a pretty straightforward process that can be learned in a very short time. However, if you’re not feeling completely confident using this  feature that’s incorporated into the object model of PHP, you may want to play with all the code samples developed in this first chapter of this series.

Final thoughts

In this initial tutorial, I walked you through the foundations of member visibility in PHP 5. In this case, you hopefully learned how to work with public and protected class properties. This is actually a no-brainer process that can be tackled with minor efforts.

In the upcoming article of the series, I’m going to teach you how to restrict the access to the properties of a class even more by declaring them private, so I don’t think you want to miss it!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan