P O L I T I C S

POLITICS – TO BETTER OUR PLANET

Archive for PHP

PHP CLASS :: Object oriented programming in PHP 4

While a large number of programmers shun the use of OOP as a programming paradigm, many more are seeing the advantages of OOP every day. Objects are here to stay – and if you don’t like them yet, give it a chance: there comes a time in every developers career when he makes the evolutionary step up to OOP.

In this article we are going explore exactly what OOP is in relation to PHP, and look at a few things you should remember about it as well. We’ll end of with a simple example of how to use it.

Objects

The first thing that we need to wrap our heads around is the principle of Classes. Put simply, a Class is an Object, and an Object is a Class. But, like an everyday object, PHP Objects have certain properties, and they can do things. A simple class might look like this:


< ?php

class human {
public $gender='Male';
}

The very basic use – and not very good use, I might add – of this simple class would be to get the gender of a human. Unfortunately, all humans instantiated below will be Male by default.

We use the class as follows:


< ?php
$Johnny = new human;

echo 'Johnny is a '. $Johnny->gender.'.';

Which will return


Johnny is a male.
               

For simple objects, that may be fine, but what if we needed to set the gender of a human as either male or female?

The Constructor

This is where we start to see the power of OOP. Consider the example below:


< ?php

class human {
public $gender;

public function __construct($gender)
{
$this->gender = $gender;
}

public function get_gender()
{
return $this->gender;
}
}

Adding the Contructor Method (function) to the class makes things a little more interesting. First of all, we can now instantiate this class like this:


< ?php
$Johnny = new human('male');

As you can see, whatever arguments you pass directly into the object on instantiation are passed into the constructor method of the object. What happens now, if you look at our constructor, is that we have assigned the value of the argument ($gender) to a Property of the object, by using $this. Let’s explore that a little more.

$this

This may sound a little loopy (no pun intended) because what on Earth is $this? Think of it as a reference to the current object. So if you have an object and you are referencing or assigning a value to $this->gender, then you are referencing or assigning a value to the gender Property of the object you are currently working with.

self::

Now, $this is a good way of referencing properties, but how do we reference Methods? Remember, a Method is a function inside an object, and gives the Object the ability to DO THINGS.

So, in order to call a Method of the Object I am working in, I can use the self:: call, as below:


< ?php

class human {
public $gender;

public function __construct($gender)
{
$this->gender = $gender;

echo self::get_gender();
}

public function get_gender()
{
return $this->gender;
}
}

What you will see now is that once the object is instantiated, it sets the value of $gender, and then runs the get_gender() function, which prints the following to the screen:

Male

This makes setting up and running methods in a current class very simple.

Inheritance

So far, things are simple. But now we take thing once step further by introducing inheritance.

Inheritance is just like it sounds – we talk about one object extending another one, and when it does, it inherits the properties and methods of the parent object.

In terms of out human class, lets try the following:


< ?php

class human {
public $gender;

public function __construct($gender)
{
$this->gender = $gender;

echo self::get_gender();
}

public function get_gender()
{
return $this->gender;
}
}

class person extends human {
public $name;
public $surname;

public static function set_name($name)
{
$this->name = $name;
}

public static function set_surname($surname)
{
$this->surname = $surname;
}

public static function get_name()
{
return $this->name;
}

public static function get_surname()
{
return $this->surname;
}
}

$Johnny = new person('male');
$Johnny->set_name('Johnny');
$Johnny->set_surname('Williams');

echo $Johnny->get_name().' '.$Johnny->get_surname().' is a '.$this->get_gender();

$Mary = new person('female');
$Mary->set_name('Mary');
$Mary->set_surname('Williams');

echo $Mary->get_name().' '.$Mary->get_surname().' is a '.$this->get_gender();

Accessors

Accessors are instructions that generally give a property of method permission to be accessible in different ways. There are three types:

public: This property or permission is accessible from anywhere in the application.

protected: This property or permission is accessible only from a class that extends the parent class.

private: This property or permission is accessible only within the current class you are working with.

The really neat thing about access is that it protects your code should other developers be working on the same project. If you don’t want them to be able to touch something, don’t give him access to it.

Advertisements

PHP CLASS : Object oriented programming in PHP 1

Object Oriented PHP for Beginners: Steps 1 – 5

For this tutorial, you should understand a few PHP basics: functions, variables, conditionals and loops.

To make things easy, the tutorial is divided into 22 steps.

Step 1:

First thing we need to do is create two PHP pages:

  • index.php
  • class_lib.php

OOP is all about creating modular code, so our object oriented PHP code will be contained in dedicated files that we will then insert into our normal PHP page using php ‘includes’.

In this case, all our OO PHP code will be in the PHP file:

  • class_lib.php

OOP revolves around a construct called a ‘class’. Classes are the cookie-cutters / templates that are used to define objects.

Step 2:

Create a simple PHP class (in class_lib.php)

Instead of having a bunch of functions, variables and code floating around willy-nilly, to design your php scripts or code libraries the OOP way, you’ll need to define/create your own classes.

You define your own class by starting with the keyword ‘class’ followed by the name you want to give your new class.

< ?php 
	class person {
 
	}
?>

Note: You enclose a class using curly braces ( { } ) … just like you do with functions.

Step 3:

Add data to your class

Classes are the blueprints for php objects – more on that later. One of the big differences between functions and classes is that a class contains both data (variables) and functions that form a package called an: ‘object’.

When you create a variable inside a class, it is called a ‘property’.

< ?php 
	class person {
		var $name;
	}
?>

Note: The data/variables inside a class (ex: var $name;) are called ‘properties’.

Step 4:

Add functions/methods to your class

In the same way that variables get a different name when created inside a class (they are called: properties,) functions also referred to (by nerds) by a different name when created inside a class – they are called ‘methods’.

A class’s methods are used to manipulate its own data / properties.

< ?php 
	class person {
		var $name;
		function set_name($new_name) {
			$this->name = $new_name;
		}
		function get_name() {
			return $this->name;
		}
	}
?>

Note: Don’t forget that in a class, variables are called ‘properties’ and functions are called ‘methods’.

Step 5:

Getter and setter functions

We’ve created two interesting functions/methods: get_name() and set_name().

These methods follow a common OOP convention that you see in many languages (including Java and Ruby) – where you create methods to ‘set’ and ‘get’ properties in a class.

Another convention is that getter and setter names should match the property names.

<?php 
	class person {
		var $name; 
		function set_name($new_name) { 
			$this->name = $new_name;  
 		}
 
   		function get_name() {
			return $this->name;
		}
	} 
?>

Note: Notice that the getter and setter names, match the associated property name.

This way, when other PHP programmers want to use your objects, they will know that if you have a method/function called ‘set_name()’, there will be a property/variable called ‘name’.

 

Object Oriented PHP for Beginners: Steps 6 – 11

Step 6:

The ‘$this’ variable

You probably noticed this line of code:

$this->name = $new_name;

The $this is a built-in variable (built into all objects) which points to the current object. Or in other words, $this is a special self-referencing variable. You use $this to access properties and to call other methods of the current class.

function get_name() {
	return $this->name;
}

Note: This may be a bit confusing for some of you … that’s because you are seeing for the first time, one of those built in OO capabilities (built into PHP5 itself) that automatically does stuff for us.

For now, just think of $this as a special OO PHP keyword. When PHP comes across $this, the PHP engine knows what to do.

… Hopefully soon, you will too!

Step 7:

Use your class in your main PHP page. (index.php)

You would never create your PHP classes directly inside your main php pages – that would help defeat the purposes of object oriented PHP in the first place!

Instead, it is always best practice to create separate php pages that only contain your classes. Then you would access your php objects/classes by including them in your main php pages with either a php ‘include’ or ‘require’.

<?php include("class_lib.php"); ?>

Note: Notice how we haven’t done anything with our class yet. We will do that next.

Step 8:

Instantiate/create your object

Classes are the blueprints/templates of php objects. Classes don’t actually become objects until you do something called: instantiation.

When you instantiate a class, you create an instance of it … thus creating the object.

In other words, instantiation is the process of creating an instance of an object in memory. What memory? The server’s memory of course!

< ?php include("class_lib.php"); ?>
< ?php 
	$stefan = new person();
? >

Note:  The variable $stefan becomes a handle/reference to our newly created person object. I call $stefan a ‘handle’, because we will use $stefan to control and use the person object.

If you run the PHP code now, you will not see anything displayed on your pages. The reason for this, is because we have not told PHP to do anything with the object we just created …

Step 9:

The ‘new’ keyword

To create an object out of a class, you need to use the ‘new’ keyword.

When creating/instantiating a class, you can optionally add brackets to the class name, as I did in the example below. To be clear, you can see in the code below how I can create multiple objects from the same class.

… From the PHP’s engine point of view, each object is its own entity.  Does that make sense?

< ?php include("class_lib.php"); ?>
< ?php 
	$stefan = new person();
	$jimmy = new person;
? >

Note:  When creating an object, be sure not to quote the class name.

For example:

$stefan = new 'person';

… will give you an error.

Step 10:

Set an objects properties

Now that we’ve created/instantiated our two separate ‘person’ objects, we can set their properties using the methods (the setters) we created.

Please keep in mind that though both our person objects ($stefan and $jimmy) are based on the same ‘person’ class, as far as php is concerned, they are totally different objects.

< ?php include("class_lib.php"); ?>
< ?php 
	$stefan = new person();
	$jimmy = new person;
	$stefan->set_name("Stefan Mischook");
	$jimmy->set_name("Nick Waddles");
? >

Step 11:

Accessing an object’s data

Now we use the getter methods to access the data held in our objects … this is the same data we inserted into our objects using the setter methods.

When accessing methods and properties of a class, you use the arrow  (->) operator.

<  ?php include("class_lib.php"); ?>
< ?php 
	$stefan = new person();
	$jimmy = new person;
 
	$stefan->set_name("Stefan Mischook");
	$jimmy->set_name("Nick Waddles");
 
	echo "Stefan's full name: " . $stefan->get_name();
	echo "Nick's full name: " . $jimmy->get_name(); 
? >

Note: The arrow operator (->) is not the same operator used with associative arrays: =>.

Congratulations, you’ve made it half way through the tutorial! Time to take a little break and have some tea … OK, maybe some beer.

In a short period of time, you’ve:

  • Designed a PHP class.
  • Generate/created a couple of objects based on your class.
  • Inserted data into your objects.
  • Retrieved data from your objects.

 

 

Object Oriented PHP for Beginners: Steps 12 – 17

Step 12:

Directly accessing properties – don’t do it!

You don’t have to use methods to access objects properties; you can directly get to them using the arrow operator (->) and the name of the variable.

For example: with the property $name (in object $stefan) you could get its value like so:

$name = $stefan->name;

Though doable, it is considered bad practice to do it because it can lead to trouble down the road. You should use getter methods instead – more on that later.

< ?php include("class_lib.php"); ?>		
< ?php 
	$stefan = new person();		
	$jimmy = new person;
 
	$stefan->set_name("Stefan Mischook");
	$jimmy->set_name("Nick Waddles");	
 
	// directly accessing properties in a class is a no-no.
	echo "Stefan's full name: ".$stefan->name;
? >

Step 13:

Constructors

All objects can have a special built-in method called a ‘constructor’. Constructors allow you to initialise your object’s properties (translation: give your properties values,) when you instantiate (create) an object.

Note: If you create a __construct() function (it is your choice,) PHP will automatically call the __construct() method/function when you create an object from your class.

The ‘construct’ method starts with two underscores (__) and the word ‘construct’.

< ?php 		
	class person {
		var $name;
		function __construct($persons_name) {		
			$this->name = $persons_name;		
		}		
 
		function set_name($new_name) {
		 	 $this->name = $new_name;
		}	
 
		function get_name() {		
		 	 return $this->name;		
		 }		
 
	}	 	
? >

For the rest of this tutorial, I’m going to stop reminding you that:

  • Functions = methods
  • Variables = properties

Since this is an OO PHP tutorial, I will now use the OO terminology.

Step 14:

Create an object with a constructor

Now that we’ve created a constructor method, we can provide a value for the $name property when we create our person objects.

You ‘feed’ the constructor method by providing a list of arguments (like you do with a function) after the class name.

For example:

$stefan = new person("Stefan Mischook");

This saves us from having to call the set_name() method reducing the amount of code. Constructors are common and are used often in PHP, Java etc.

< ?php include("class_lib.php"); ?>		
< ?php 
	$stefan = new person("Stefan Mischook");
	echo "Stefan's full name: ".$stefan->get_name();
? >

This is just a tiny example of how the mechanisms built into OO PHP can save you time and reduce the amount of code you need to write. Less code means fewer bugs.

Step 15:

Restricting access to properties using ‘access modifiers’

One of the fundamental principles in OOP is ‘encapsulation’. The idea is that you create cleaner better code, if you restrict access to the data structures (properties) in your objects.

You restrict access to class properties using something called ‘access modifiers’. There are 3 access modifiers:

  1. public
  2. private
  3. protected

‘Public’ is the default modifier.

< ?php 		
	class person {		
	var $name;		
		public $height;		
		protected $social_insurance;
		private $pinn_number;
 
		function __construct($persons_name) {		
			$this->name = $persons_name;		
		}		
 
		function set_name($new_name) {   	
			$this->name = $new_name;
		}	
 
		function get_name() {
			return $this->name;
		}		
 
	}
? >

Note: When you declare a property with the ‘var’ keyword, it is considered ‘public’.

Step 16:

Restricting access to properties: part 2

When you declare a property as ‘private’, only the same class can access the property.

When a property is declared ‘protected’, only the same class and classes derived from that class can access the property – this has to do with inheritance …more on that later.

Properties declared as ‘public’ have no access restrictions, meaning anyone can access them.

To help you understand this (probably) foggy aspect of OOP, try out the following code and watch how PHP reacts. Tip: read the comments in the code for more information:

< ?php include("class_lib.php"); ?>
< ?php  
	$stefan = new person("Stefan Mischook");   
	echo "Stefan's full name: " .  $stefan->get_name() ;  
 
	/*  
	Since $pinn_number was declared private, this line of code 
	will generate an error. Try it out!   
	*/  
 
	echo "Tell me private stuff: ".$stefan->pinn_number;  
? >

Note: If you try to access a private property/variable outside of the class, you will get this:

'Fatal error: Cannot access private property person::$pinn_number in ...'

Step 17:

Restricting access to methods

Like properties, you can control access to methods using one of the three
access modifiers:

  1. public
  2. protected
  3. private

Why do we have access modifiers?

In a nutshell: it comes down to control -it is makes sense to control how people use classes.

The reasons for access modifiers and other OO constructs, can be tricky to understand … especially since we are just beginners here. So give yourself a chance!

That said, we can (summarize and) say that many OOP constructs exist with idea the many programmers may be working together on a project.

< ?php 
	class person {  
		var $name;  
 
		public $height;  
		protected $social_insurance;  
		private $pinn_number;
 
		function __construct($persons_name){   
		   $this->name = $persons_name;  
		}       
 
		private function get_pinn_number(){
			return
			$this->pinn_number;  
		}       
	}   
? >

Notes: Since the method get_pinn_number() is ‘private’, the only place you can use this method is in the same class – typically in another method. If you wanted to call/use this method directly in your PHP pages, you would need to declare it ‘public’.

Object Oriented PHP for Beginners: Steps 18 – 22

Step 18:

Inheritance – reusing code the OOP way

Inheritance is a fundamental capability/construct in OOP where you can use one class, as the base/basis for another class … or many other classes.

Why do it?

Doing this allows you to efficiently reuse the code found in your base class.

Say, you wanted to create a new ’employee’ class … since we can say that ’employee’ is a type/kind of ‘person’, they will share common properties and methods.

… Making some sense?

In this type of situation, inheritance can make your code lighter … because you are reusing the same code in two different classes. But unlike ‘old-school’ PHP:

  1. You only have to type the code out once.
  2. The actual code being reused, can be reused in many (unlimited) classes
    but it is only typed out in one place … conceptually, this is sort-of
    like PHP includes().

Take a look at the sample PHP code:

// 'extends' is the keyword that enables inheritance
class employee extends person 
{
	function __construct($employee_name) {
		$this->set_name($employee_name);
	}
}

Step 19:

Reusing code with inheritance: part 2

Because the class ’employee’ is based on the class ‘person’, ’employee’ automatically has all the public and protected properties and methods of ‘person’.

Nerd note: Nerds would say that ’employee’ is a type of person.

The code:

class employee extends person 
{
	function __construct($employee_name){
		$this->set_name($employee_name);
	}
}

Notice how we are able to use set_name() in ’employee’, even though we did not declare that method in the ’employee’ class. That’s because we already created set_name() in the class ‘person’.

Nerd Note: the ‘person’ class is called (by nerds,) the ‘base’ class or the ‘parent’ class because it’s the class that the ’employee’ is based on. This class hierarchy can become important down the road when your projects become more complex.

Step 20:

Reusing code with inheritance: part 3

As you can see in the code snippet below, we can call get_name on our ’employee’ object, courtesy of ‘person’.

The code:

	<?phpinclude("class_lib.php"); ?>
	<?php
		// Using our PHP objects in our PHP pages. 
		$stefan = new person("Stefan Mischook");
		echo "Stefan's full name: " . $stefan->get_name();
 
		$james = new employee("Johnny Fingers");
		echo "---> " . $james->get_name();
	?>

This is a classic example of how OOP can reduce the number of lines of code (don’t have to write the same methods twice) while still keeping your code modular and much easier to maintain.

Step 21:

Overriding methods

Sometimes (when using inheritance,) you may need to change how a method works from the base class.

For example, let’s say set_name() method in the ’employee’ class, had to do something different than what it does in the ‘person’ class.

You ‘override’ the ‘person’ classes version of set_name(), by declaring the same method in ’employee’.

The code snippet:

<?php
	class person 
	{
		protected function set_name($new_name) {
			if ($new_name != "Jimmy Two Guns") {
				$this->name = strtoupper($new_name);
			}
		}
	} 
 
	class employee extends person 
	{
		protected function set_name($new_name) {
			if ($new_name == "Stefan Sucks") {
				$this->name = $new_name;
			}
		}
	}
?>

Notice how set_name() is different in the ’employee’ class from the version found in the parent class: ‘person’.

Step 22:

Overriding methods: part 2

Sometimes you may need to access your base class’s version of a method you overrode in the derived (sometimes called ‘child’) class.

In our example, we overrode the set_name() method in the ’employee’ class. Now I’ve used this code:

person::set_name($new_name);

… to access the parent class’ (person) version of the set_name() method.

The code:

<?php
	class person 
	{
		// explicitly adding class properties are optional - but 
		// is good practice
		var $name;	 
		function __construct($persons_name) {
			$this->name = $persons_name;
		 }
 
		 public function get_name() {
		 	return $this->name;
		 }
 
		 // protected methods and properties restrict access to 
		 // those elements.
		 protected function set_name($new_name) {
		 	 if ($this->name !=  "Jimmy Two Guns") {
		 	 	$this->name = strtoupper($new_name);
		 	 } 
		}
	} 
 
	// 'extends' is the keyword that enables inheritance
	class employee extends person 
	{
		protected function set_name($new_name) {
		if ($new_name ==  "Stefan Sucks") {
			$this->name = $new_name;
		}
	 	else if ($new_name ==  "Johnny Fingers") {
			person::set_name($new_name);
		} 
	}
 
	function __construct($employee_name) 
	{
		$this->set_name($employee_name);
	}
}
?>

Notes: Using the symbol:

::

… allows you to specifically name the class where you want PHP to search for a method:

'person::set_name()'

… tells PHP to search for set_name() in the ‘person’ class.

There is also a shortcut if you just want refer to current class’s parent – by using the ‘parent’ keyword.

The code:

protected function set_name($new_name) 
{	
	if ($new_name ==  "Stefan Sucks") {
		$this->name = $new_name;	
	 }	
	 else if ($new_name ==  "Johnny Fingers") {
		parent::set_name($new_name);	
	}	
}

 

PHP CLASS : Object oriented programming in PHP 2

Object-oriented programming is a style of coding that allows developers to group similar tasks into classes. This helps keep code following the tenet “don’t repeat yourself” (DRY) and easy-to-maintain.

“Object-oriented programming is a style of coding that allows developers to group similar tasks into classes.”

One of the major benefits of DRY programming is that, if a piece of information changes in your program, usually only one change is required to update the code. One of the biggest nightmares for developers is maintaining code where data is declared over and over again, meaning any changes to the program become an infinitely more frustrating game of Where’s Waldo? as they hunt for duplicated data and functionality.

OOP is intimidating to a lot of developers because it introduces new syntax and, at a glance, appears to be far more complex than simple procedural, or inline, code. However, upon closer inspection, OOP is actually a very straightforward and ultimately simpler approach to programming.

Before you can get too deep into the finer points of OOP, a basic understanding of the differences between objects and classes is necessary. This section will go over the building blocks of classes, their different capabilities, and some of their uses.

Photos by Instant Jefferson and John Wardell

Developers start talking about objects and classes, and they appear to be interchangeable terms. This is not the case, however.

Right off the bat, there’s confusion in OOP: seasoned developers start talking about objects and classes, and they appear to be interchangeable terms. This is not the case, however, though the difference can be tough to wrap your head around at first.

A class, for example, is like a blueprint for a house. It defines the shape of the house on paper, with relationships between the different parts of the house clearly defined and planned out, even though the house doesn’t exist.

An object, then, is like the actual house built according to that blueprint. The data stored in the object is like the wood, wires, and concrete that compose the house: without being assembled according to the blueprint, it’s just a pile of stuff. However, when it all comes together, it becomes an organized, useful house.

Classes form the structure of data and actions and use that information to build objects. More than one object can be built from the same class at the same time, each one independent of the others. Continuing with our construction analogy, it’s similar to the way an entire subdivision can be built from the same blueprint: 150 different houses that all look the same but have different
families and decorations inside.

The syntax to create a class is pretty straightforward: declare a class using theclass keyword, followed by the name of the class and a set of curly braces ({}):

After creating the class, a new class can be instantiated and stored in a variable using the new keyword:

To see the contents of the class, use var_dump():

Try out this process by putting all the preceding code in a new file called test.phpin [your local] testing folder:

Load the page in your browser at http://localhost/test.php and the following should display:

In its simplest form, you’ve just completed your first OOP script.

To add data to a class, properties, or class-specific variables, are used. These work exactly like regular variables, except they’re bound to the object and therefore can only be accessed using the object.

To add a property to MyClass, add the following code to your script:

The keyword public determines the visibility of the property, which you’ll learn about a little later in this chapter. Next, the property is named using standard variable syntax, and a value is assigned (though class properties do not need an initial value).

To read this property and output it to the browser, reference the object from which to read and the property to be read:

Because multiple instances of a class can exist, if the individual object is not referenced, the script would be unable to determine which object to read from. The use of the arrow (->) is an OOP construct that accesses the contained properties and methods of a given object.

Modify the script in test.php to read out the property rather than dumping the whole class by modifying the code as shown:

Reloading your browser now outputs the following:

Methods are class-specific functions. Individual actions that an object will be able to perform are defined within the class as methods.

For instance, to create methods that would set and get the value of the class property $prop1, add the following to your code:

Note — OOP allows objects to reference themselves using $this. When working within a method, use $this in the same way you would use the object name outside the class.

To use these methods, call them just like regular functions, but first, reference the object they belong to. Read the property from MyClass, change its value, and read it out again by making the modifications below:

Reload your browser, and you’ll see the following:

“The power of OOP becomes apparent when using multiple instances of the
same class.”

When you load the results in your browser, they read as follows:

As you can see, OOP keeps objects as separate entities, which makes for easy separation of different pieces of code into small, related bundles.

To make the use of objects easier, PHP also provides a number of magic methods, or special methods that are called when certain common actions occur within objects. This allows developers to perform a number of useful tasks with relative ease.

When an object is instantiated, it’s often desirable to set a few things right off the bat. To handle this, PHP provides the magic method __construct(), which is called automatically whenever a new object is
created.

For the purpose of illustrating the concept of constructors, add a constructor toMyClass that will output a message whenever a new instance of the class is created:

Note__CLASS__ returns the name of the class in which it is called; this is what is known as a magic constant. There are several available magic constants, which you can read more about in the PHP manual.

Reloading the file in your browser will produce the following result:

To call a function when the object is destroyed, the __destruct() magic method is available. This is useful for class cleanup (closing a database connection, for instance).

Output a message when the object is destroyed by defining the magic method
__destruct() in MyClass:

With a destructor defined, reloading the test file results in the following output:

“When the end of a file is reached, PHP automatically releases all resources.”

To explicitly trigger the destructor, you can destroy the object using the
function unset():

Now the result changes to the following when loaded in your browser:

To avoid an error if a script attempts to output MyClass as a string, another magic method is used called __toString().

Without __toString(), attempting to output the object as a string results in a fatal error. Attempt to use echo to output the object without a magic method in place:

This results in the following:

To avoid this error, add a __toString() method:

In this case, attempting to convert the object to a string results in a call to thegetProperty() method. Load the test script in your browser to see the result:

Tip — In addition to the magic methods discussed in this section, several others are available. For a complete list of magic methods, see the PHP manual page.

Classes can inherit the methods and properties of another class using theextends keyword. For instance, to create a second class that extends MyClass and adds a method, you would add the following to your test file:

Upon reloading the test file in your browser, the following is output:

To change the behavior of an existing property or method in the new class, you can simply overwrite it by declaring it again in the new class:

This changes the output in the browser to:

To add new functionality to an inherited method while keeping the original method intact, use the parent keyword with the scope resolution operator (::):

This outputs the result of both the parent constructor and the new class’s constructor:

For added control over objects, methods and properties are assigned visibility. This controls how and from where properties and methods can be accessed. There are three visibility keywords: public, protected, and private. In addition to its visibility, a method or property can be declared as static, which allows them to be accessed without an instantiation of the class.

“For added control over objects, methods and properties are assigned visibility.”

Note — Visibility is a new feature as of PHP 5. For information on OOP compatibility with PHP 4, see the PHP manual page.

All the methods and properties you’ve used so far have been public. This means that they can be accessed anywhere, both within the class and externally.

When a property or method is declared protected, it can only be accessed within the class itself or in descendant classes (classes that extend the class containing the protected method).

Declare the getProperty() method as protected in MyClass and try to access it directly from outside the class:

Upon attempting to run this script, the following error shows up:

Now, create a new method in MyOtherClass to call the getProperty() method:

This generates the desired result:

A property or method declared private is accessible only from within the class that defines it. This means that even if a new class extends the class that defines a private property, that property or method will not be available at all within the child class.

To demonstrate this, declare getProperty() as private in MyClass, and attempt to call callProtected() from
MyOtherClass:

Reload your browser, and the following error appears:

A method or property declared static can be accessed without first instantiating the class; you simply supply the class name, scope resolution operator, and the property or method name.

“One of the major benefits to using static properties is that they keep their stored values for the duration of the script.”

To demonstrate this, add a static property called $count and a static method calledplusOne() to MyClass. Then set up a do...while loop to output the incremented value of $count as long as the value is less than 10:

Note — When accessing static properties, the dollar sign
($) comes after the scope resolution operator.

When you load this script in your browser, the following is output:

“The DocBlock commenting style is a widely
accepted method of documenting classes.”

While not an official part of OOP, the DocBlock commenting style is a widely accepted method of documenting classes. Aside from providing a standard for
developers to use when writing code, it has also been adopted by many of the most popular software development kits (SDKs), such as Eclipse and NetBeans, and will be used to generate code hints.

A DocBlock is defined by using a block comment that starts with an additional asterisk:

The real power of DocBlocks comes with the ability to use tags, which start with an at symbol (@) immediately followed by the tag name and the value of the tag.DocBlock tags allow developers to define authors of a file, the license for a class, the property or method information, and other useful information.

The most common tags used follow:

  • @author: The author of the current element (which might be a class, file, method, or any bit of code) are listed using this tag. Multiple author tags can be used in the same DocBlock if more than one author is credited. The format for the author name is John Doe <john.doe@email.com>.
  • @copyright: This signifies the copyright year and name of the copyright holder for the current element. The format is 2010 Copyright Holder.
  • @license: This links to the license for the current element. The format for the license information is
    http://www.example.com/path/to/license.txt License Name.
  • @var: This holds the type and description of a variable or class property. The format is type element description.
  • @param: This tag shows the type and description of a function or method parameter. The format is type $element_name element description.
  • @return: The type and description of the return value of a function or method are provided in this tag. The format is type return element description.

A sample class commented with DocBlocks might look like this:

Once you scan the preceding class, the benefits of DocBlock are apparent: everything is clearly defined so that the next developer can pick up the code andnever have to wonder what a snippet of code does or what it should contain.

There’s not really a right and wrong way to write code. That being said, this section outlines a strong argument for adopting an object-oriented approach in software development, especially in large applications.

“While it may be daunting at first, OOP actually provides an easier approach to dealing with data.”

While it may be daunting at first, OOP actually provides an easier approach to dealing with data. Because an object can store data internally, variables don’t need to be passed from function to function to work properly.

Also, because multiple instances of the same class can exist simultaneously, dealing with large data sets is infinitely easier. For instance, imagine you have two people’s information being processed in a file. They need names, occupations, and ages.

Here’s the procedural approach to our example:

When executed, the code outputs the following:

While this code isn’t necessarily bad, there’s a lot to keep in mind while coding. The array of the affected person’s attributes must be passed and returned from each function call, which leaves margin for error.

To clean up this example, it would be desirable to leave as few things up to the developer as possible. Only absolutely essential information for the current operation should need to be passed to the functions.

This is where OOP steps in and helps you clean things up.

Here’s the OOP approach to our example:

This outputs the following in the browser:

There’s a little bit more setup involved to make the approach object oriented, but after the class is defined, creating and modifying people is a breeze; a person’s information does not need to be passed or returned from methods, and only absolutely essential information is passed to each method.

“OOP will significantly reduce your workload if implemented properly.”

On the small scale, this difference may not seem like much, but as your applications grow in size, OOP will significantly reduce your workload if implemented properly.

TipNot everything needs to be object oriented. A quick function that handles something small in one place inside the application does not necessarily need to be wrapped in a class. Use your best judgment when deciding between object-oriented and procedural approaches.

Another benefit of OOP is how well it lends itself to being easily packaged and cataloged. Each class can generally be kept in its own separate file, and if a uniform naming convention is used, accessing the classes is extremely simple.

Assume you’ve got an application with 150 classes that are called dynamically through a controller file at the root of your application filesystem. All 150 classes follow the naming convention class.classname.inc.php and reside in the incfolder of your application.

The controller can implement PHP’s __autoload() function to dynamically pull in only the classes it needs as they are called, rather than including all 150 in the controller file just in case or coming up with some clever way of including the files in your own code:

Having each class in a separate file also makes code more portable and easier to reuse in new applications without a bunch of copying and pasting.

PHP Class : Object oriented programming in PHP

Object Oriented Concepts

Before we go in detail, lets define important terms related to Object Oriented Programming.

  • Class − This is a programmer-defined data type, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object.
  • Object − An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance.
  • Member Variable − These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. These variables are called attribute of the object once an object is created.
  • Member function − These are the function defined inside a class and are used to access object data.
  • Inheritance − When a class is defined by inheriting existing function of a parent class then it is called inheritance. Here child class will inherit all or few member functions and variables of a parent class.
  • Parent class − A class that is inherited from by another class. This is also called a base class or super class.
  • Child Class − A class that inherits from another class. This is also called a subclass or derived class.
  • Polymorphism − This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it make take different number of arguments and can do different task.
  • Overloading − a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation.
  • Data Abstraction − Any representation of data in which the implementation details are hidden (abstracted).
  • Encapsulation − refers to a concept where we encapsulate all the data and member functions together to form an object.
  • Constructor − refers to a special type of function which will be called automatically whenever there is an object formation from a class.
  • Destructor − refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope.

Defining PHP Classes

The general form for defining a new class in PHP is as follows −

< ?php
   class phpClass {
      var $var1;
      var $var2 = "constant string";
      
      function myfunc ($arg1, $arg2) {
         [..]
      }
      [..]
   }
? >

Here is the description of each line −

  • The special form class, followed by the name of the class that you want to define.
  • A set of braces enclosing any number of variable declarations and function definitions.
  • Variable declarations start with the special form var, which is followed by a conventional $ variable name; they may also have an initial assignment to a constant value.
  • Function definitions look much like standalone PHP functions but are local to the class and will be used to set and access object data.

Example

Here is an example which defines a class of Books type −

< ?php
   class Books {
      /* Member variables */
      var $price;
      var $title;
      
      /* Member functions */
      function setPrice($par){
         $this->price = $par;
      }
      
      function getPrice(){
         echo $this->price ."<br/>";
      }
      
      function setTitle($par){
         $this->title = $par;
      }
      
      function getTitle(){
         echo $this->title ." <br/>";
      }
   }
? >

The variable $this is a special variable and it refers to the same object ie. itself.

Creating Objects in PHP

Once you defined your class, then you can create as many objects as you like of that class type. Following is an example of how to create object using newoperator.

$physics = new Books;
$maths = new Books;
$chemistry = new Books;

Here we have created three objects and these objects are independent of each other and they will have their existence separately. Next we will see how to access member function and process member variables.

Calling Member Functions

After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only.

Following example shows how to set title and prices for the three books by calling member functions.

$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );

$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );

Now you call another member functions to get the values set by in above example −

$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();

This will produce the following result −

Physics for High School
Advanced Chemistry
Algebra
10
15
7

Constructor Functions

Constructor Functions are special type of functions which are called automatically whenever an object is created. So we take full advantage of this behaviour, by initializing many things through constructor functions.

PHP provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function.

Following example will create one constructor for Books class and it will initialize price and title for the book at the time of object creation.

function __construct( $par1, $par2 ) {
   $this->price = $par1;
   $this->title = $par2;
}

Now we don’t need to call set function separately to set price and title. We can initialize these two member variables at the time of object creation only. Check following example below −

$physics = new Books( "Physics for High School", 10 );
$maths = new Books ( "Advanced Chemistry", 15 );
$chemistry = new Books ("Algebra", 7 );

/* Get those set values */
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();

$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();

This will produce the following result −

  Physics for High School
  Advanced Chemistry
  Algebra
  10
  15
  7

Destructor

Like a constructor function you can define a destructor function using function__destruct(). You can release all the resources with-in a destructor.

Inheritance

PHP class definitions can optionally inherit from a parent class definition by using the extends clause. The syntax is as follows −

class Child extends Parent {
   <definition body>
}

The effect of inheritance is that the child class (or subclass or derived class) has the following characteristics −

  • Automatically has all the member variable declarations of the parent class.
  • Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent.

Following example inherit Books class and adds more functionality based on the requirement.

class Novel extends Books {
   var publisher;
   
   function setPublisher($par){
      $this->publisher = $par;
   }
   
   function getPublisher(){
      echo $this->publisher. "<br />";
   }
}

Now apart from inherited functions, class Novel keeps two additional member functions.

Function Overriding

Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class.

In the following example getPrice and getTitle functions are overridden to return some values.

function getPrice() {
   echo $this->price . "<br/>";
   return $this->price;
}
   
function getTitle(){
   echo $this->title . "<br/>";
   return $this->title;
}

Public Members

Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be accessed in three possible situations −

  • From outside the class in which it is declared
  • From within the class in which it is declared
  • From within another class that implements the class in which it is declared

Till now we have seen all members as public members. If you wish to limit the accessibility of the members of a class then you define class members asprivate or protected.

Private members

By designating a member private, you limit its accessibility to the class in which it is declared. The private member cannot be referred to from classes that inherit the class in which it is declared and cannot be accessed from outside the class.

A class member can be made private by using private keyword infront of the member.

class MyClass {
   private $car = "skoda";
   $driver = "SRK";
   
   function __construct($par) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
   
   function myPublicFunction() {
      return("I'm visible!");
   }
   
   private function myPrivateFunction() {
      return("I'm  not visible outside!");
   }
}

When MyClass class is inherited by another class using extends, myPublicFunction() will be visible, as will $driver. The extending class will not have any awareness of or access to myPrivateFunction and $car, because they are declared private.

Protected members

A protected property or method is accessible in the class in which it is declared, as well as in classes that extend that class. Protected members are not available outside of those two kinds of classes. A class member can be made protected by using protected keyword in front of the member.

Here is different version of MyClass −

class MyClass {
   protected $car = "skoda";
   $driver = "SRK";

   function __construct($par) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
   
   function myPublicFunction() {
      return("I'm visible!");
   }
   
   protected function myPrivateFunction() {
      return("I'm  visible in child class!");
   }
}

Interfaces

Interfaces are defined to provide a common function names to the implementers. Different implementors can implement those interfaces according to their requirements. You can say, interfaces are skeletons which are implemented by developers.

As of PHP5, it is possible to define an interface, like this −

interface Mail {
   public function sendMail();
}

Then, if another class implemented that interface, like this −

class Report implements Mail {
   // sendMail() Definition goes here
}

Constants

A constant is somewhat like a variable, in that it holds a value, but is really more like a function because a constant is immutable. Once you declare a constant, it does not change.

Declaring one constant is easy, as is done in this version of MyClass −

class MyClass {
   const requiredMargin = 1.7;
   
   function __construct($incomingValue) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
}

In this class, requiredMargin is a constant. It is declared with the keyword const, and under no circumstances can it be changed to anything other than 1.7. Note that the constant’s name does not have a leading $, as variable names do.

Abstract Classes

An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class with the keyword abstract, like this −

When inheriting from an abstract class, all methods marked abstract in the parent’s class declaration must be defined by the child; additionally, these methods must be defined with the same visibility.

abstract class MyAbstractClass {
   abstract function myAbstractFunction() {
   }
}

Note that function definitions inside an abstract class must also be preceded by the keyword abstract. It is not legal to have abstract function definitions inside a non-abstract class.

Static Keyword

Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can).

Try out following example −

<?php
   class Foo {
      public static $my_static = 'foo';
      
      public function staticValue() {
         return self::$my_static;
      }
   }
	
   print Foo::$my_static . "\n";
   $foo = new Foo();
   
   print $foo->staticValue() . "\n";
?>

Final Keyword

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

Following example results in Fatal error: Cannot override final method BaseClass::moreTesting()

<?php

   class BaseClass {
      public function test() {
         echo "BaseClass::test() called<br>";
      }
      
      final public function moreTesting() {
         echo "BaseClass::moreTesting() called<br>";
      }
   }
   
   class ChildClass extends BaseClass {
      public function moreTesting() {
         echo "ChildClass::moreTesting() called<br>";
      }
   }
?>

Calling parent constructors

Instead of writing an entirely new constructor for the subclass, let’s write it by calling the parent’s constructor explicitly and then doing whatever is necessary in addition for instantiation of the subclass. Here’s a simple example −

class Name {
   var $_firstName;
   var $_lastName;
   
   function Name($first_name, $last_name) {
      $this->_firstName = $first_name;
      $this->_lastName = $last_name;
   }
   
   function toString() {
      return($this->_lastName .", " .$this->_firstName);
   }
}
class NameSub1 extends Name {
   var $_middleInitial;
   
   function NameSub1($first_name, $middle_initial, $last_name) {
      Name::Name($first_name, $last_name);
      $this->_middleInitial = $middle_initial;
   }
   
   function toString() {
      return(Name::toString() . " " . $this->_middleInitial);
   }
}

In this example, we have a parent class (Name), which has a two-argument constructor, and a subclass (NameSub1), which has a three-argument constructor. The constructor of NameSub1 functions by calling its parent constructor explicitly using the :: syntax (passing two of its arguments along) and then setting an additional field. Similarly, NameSub1 defines its non constructor toString() function in terms of the parent function that it overrides.

NOTE − A constructor can be defined with the same name as the name of a class. It is defined in above example.

Update column with random unique number – from to

MySQL: Add or Insert Random Number

Sometimes, we would like to insert a random value into a MySQL table, for example, to test a website using random data. That is, how it works:

UPDATE tab SET col=FLOOR(5+(RAND()*(10-5+1)));

This function sets in the table “tab” the column “col” to a random value between 5 and 10. To create other random data, simply substitute the values 5 and 10 with other numbers or use the variables of this PHP function for your boundaries:

$min = 5;
$max = 10;
$query = "UPDATE tab SET col=FLOOR($min+(RAND()*($max-$min+1)))";

For numbers between 0 and a maximum value (here $max), the command simplifies to:

UPDATE tab SET col=FLOOR(RAND()*$max+1);

In some cases, we want to add a random number to an existing value in a column. This can be done with this MySQL command:

UPDATE tab SET col=spalte+FLOOR(RAND()*$max+1);

Example with PHP and MySQL code:

< ?php
include “include/connexion.php”;
$min = 100000;
$max = 999999;
$query = “UPDATE  producttable SET pin=FLOOR($min+(RAND()*($max-$min+1))) WHERE pin = ””;
mysql_query ($query);
? >

 

 

Of course you can also use the PHP function from above in this case.

 

Saving multiple checkbox values in MySQL and PHP

Insert.php

HTML FIle

 

 

EXECUTION FILE

 

 

 

 

 

————————————– show selected checkboxes.php  ———————-

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>Checkbox : </title>
</head>

<?php

$sql = new mysqli(‘localhost’,’root’,”,’test’);
$query = $sql->query(“SELECT * FROM `checkboxlanguage` WHERE chkbx_id=1 “);
$result = $query->fetch_object();
$x = $result->chkbx_name;
// Here I have some white space – that needs to clear
$x = preg_replace(‘/\s+/’, ”, $x);

// $WordsToFind = “Safety,Stationery,Print,Packaging,Exhibition,Web,3D,LetturaInglese”;
$WordsToFind = explode(‘,’,$x);

$text = “LetturaInglese,Engscrittura,Engespressione,lastone “;

$text = explode(“,”, $text);

//returns array of matched values between the two arrays
$checked_boxes = array_intersect($text, $WordsToFind);
?>

<body>
<form name”xx” method=”post” action=”checkboxupdatefinalexec.php”>
<label style=”width:125px;”><input type=”checkbox” <?php echo (in_array(‘LetturaInglese’, $checked_boxes)) ? “checked” : “” ?> name=”hotbuttons[]” id=”LetturaInglese” value=”LetturaInglese” />LetturaInglese</label>
<label style=”width:125px;”><input type=”checkbox” <?php echo (in_array(‘Engscrittura’, $checked_boxes)) ? “checked” : “” ?> name=”hotbuttons[]” id=”Engscrittura” value=”Engscrittura” />Engscrittura</label>
<label style=”width:125px;”><input type=”checkbox” <?php echo (in_array(‘Engespressione’, $checked_boxes)) ? “checked” : “” ?> name=”hotbuttons[]” id=”Engespressione” value=”Engespressione” />Engespressione</label>

<p>&nbsp;</p>
<p>&nbsp;</p>
<p>
<label>
<input type=”submit” name=”Submit” value=”Submit” />
</label>
</p>
</form></body>

</html>

———————————— update.action.php———————————

<?php
include(“include/conn.php”);

$code = 1;

$rajascode = $_POST[‘hotbuttons’];
$allchkbxtgthr = “”;
foreach ($rajascode as $checkboxcode) {
$allchkbxtgthr .= $checkboxcode . “, “;
}

// clean text with space to read -> not important though
$allchkbxtgthr = substr($allchkbxtgthr, 0, -2);

$stmt = $mysqli->prepare(“UPDATE checkboxlanguage SET chkbx_name = ‘$allchkbxtgthr’ WHERE chkbx_id = ‘$code'”);
$stmt->execute();
$stmt->close();

?>