Login

Working with Private Properties to Protect PHP 5 Class Data

Welcome to the second installment of the series, “Protecting the data of PHP 5 classes with member visibility.” It is made up of six comprehensive tutorials and provides you with a guide to help you get started using member visibility with PHP 5. It also complements the corresponding theoretical concepts with illustrative hands-on examples.

One of the most useful features that was introduced into the improved object model of PHP 5 is “member visibility.” It provides PHP developers with the ability to specify the level of access each data member of a class will have in the context of a given application. This helpful characteristic of the language allows the user to declare methods and properties of a certain class that will be available in the global scope via the “public” keyword. It also establishes more restrictive access levels by using the “protected” and “private” reserved words.

That being said, it’s time to refresh the concepts that were deployed in the last episode of the series, in case you haven’t had the chance to read it yet. Simply put, in that article, I developed a few basic hands-on examples aimed specifically at demonstrating how to declare and work with public and protected properties defined within a primitive data saving class. This came in handy for storing some simple strings in a specified text file.

In the first case, the properties of the class were declared public, meaning they could be directly accessed from outside the class in question. In the second case, the same properties were defined as protected, implying that they could only be retrieved from inside the originating class and from their eventual subclasses as well.

So to summarize, I’ve already covered the use of public and protected class properties in PHP 5. Thus, the next step in this learning process will consist of showing you how to work with private properties. Sounds pretty interesting, right?

So, let’s not waste more time with preliminaries and see how to use private properties when working with PHP 5 classes. Let’s get going!

{mospagebreak title=A review of public and protected class properties in PHP 5}

In the introduction, I provided you with a quick reference regarding the use of public and protected class properties in PHP 5. However, I’d like to complement this theory with the hands-on examples developed in the preceding article of the series. This way, you can tackle this topic from a practical point of view.

Having said that, please take a look at the following code samples, which demonstrate how to use both public and protected properties using the same sample class. Here they are:

(example using public properties with a data saving class)

// 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;

}

}

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!

At this point, you should feel pretty satisfied, since the hands-on examples listed above give you a clear idea of how to work with public and protected properties using the same sample “DataSaver” class. In the first case, you can see that the properties in question are accessible in the global scope, since they’ve been declared public. In the second example, the PHP interpreter triggers a few fatal errors when trying to access the properties publicly, because the mentioned properties have been defined as protected. Not too hard to grasp, is it?

So far, so good. Now that you’ve hopefully learned the basic concepts that surround the use of public and protected properties with PHP 5 classes, it’s time to explore more useful aspects of the utilization of member visibility.

Even when protected properties can’t be accessed directly in the global scope, they’re not restricted when used by one or more subclasses derived from the pertinent parent. Therefore, in the following section, I’m going to create another practical example for you that will recreate the scenario described above.

In order to see how this brand new example will be developed, go ahead and read the next few lines. They’re only one click away.

{mospagebreak title=Extending the use of protected class properties: working with a subclass}

As I explained in the prior section, the properties of a class that have been declared protected can be accessed freely by any subclass derived from the corresponding parent. In order to demonstrate this concept, below I coded a basic example that shows how the protected properties of the previous “DataSaver” class can be retrieved by a subclass.

Here’s the code sample; examine it in detail, please:

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;

}

}

// extends ‘DataSaver’ class and try to access protected properties

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;

}

}

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

/* displays the following

This string of data will be saved to a target file!

*/

}

catch(Exception $e){

echo $e->getMessage();

exit();

}

Now things are getting really interesting! As you can see, first, I derived a simple subclass from the pertinent “DataSaver” parent, and then used the brand new “fetch()” method to access the protected “$filePath” property. In doing so, I’m demonstrating how a protected property can be retrieved from inside a child class. Quite simple to understand, right?

All right, at this stage you’ve hopefully learned how to get access to a pair of protected properties defined by a parent using a child class. So the question is: what comes next?

Well, as I said in the beginning of this article, PHP 5 supports the definition of private properties via the “private” keyword. Thus, in the section to come, I’m going to teach you how to work with properties that have that specific level of visibility.

Naturally, in order to learn more about this useful topic, you’ll have to click on the link below and keep reading.

{mospagebreak title=Defining private class properties}

If you found working with public and protected properties of a given PHP 5 class easy, then it’s quite probable that you’ll feel the same way when it comes to using private data members. By definition, any class property declared private can only be accessed from inside the originating class. That’s all.

However, even though the above definition is very intuitive, it’s necessary to complement it adequately with a practical example. With that idea in mind, in the next few lines, I’m going to list the signature of the same “DataSaver” class that you saw earlier, but this time, its respective properties will be declared private.

The brand new definition of this sample class looks like this:

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

public function getFilePath(){

return $this->filePath;

}

// get data via an accessor

public function getData(){

return $this->data;

}

}

As you can see, the signature of the above “DataSaver” class remains practically the same, with the exception of the level of visibility assigned to its respective $data and $filePath properties, since they’ve been declared private.

Obviously, this implies that the properties in question can only be accessed from inside the originating class, and any attempt to retrieve them from a different scope will result in a fatal error being triggered by the PHP interpreter.

This condition is clearly reflected by the following hands-on example:

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

// try to print value of private 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

Cannot access private property DataSaver::$filePath in path/to/file/

*/

}

catch(Exception $e){

echo $e->getMessage();

exit();

}

In the previous example, the private $data and $filePath properties are erroneously accessed from the global scope, which naturally made the PHP engine fire up a fatal error, as indicated above.

With this final example, I’ll assume that you’re already armed with the required background to understand how to declare the level of visibility for the properties defined by a specific PHP 5 class. However, you can use all of the code samples included here to improve your existing skills in this crucial topic.

Final thoughts

Throughout this second part of the series, I provided you with an introductory guide to using private class properties in PHP 5. Nonetheless, there are some additional aspects of this subject that need to be explored in more detail, such as accessing private data members by way of subclasses and accessors.

But all of these interesting topics will be covered in the next part, so you don’t have any excuse to miss it!