PHP simple introduction to objects

Object oriented programming ( OOP ) makes the world go around. As a user you may not know the underlying implementation of the software you use, however it's extremely likely that the software uses OOP techniques.

As a beginning php developer it is essential to learn how objects work and begin to experiment with how they are used. Here is some example code to get you started along the OOP path.

 
class my_first_class {
	private $granted = false;
	public $first_name = '';
 
	function __construct() {
		// this code runs when the object is created
	}
 
	function grant() {
		if ( ! empty($this->first_name) ) {
			$this->granted = true;
		} else {
			$this->granted = false;
		}
	}
 
	function is_granted() {
		return $this->granted;
	}
}
 
 

The above class ( object definition ) sets up two variables. The granted variable is private, which means it cannot be accessed outside the class. The first_name variable is public, which means it can be accessed outside the class.

There are two functions, grant() checks if the first name is blank, if it's not it sets the granted variable to true. is_granted() returns the granted variable value.

Here is some examples on using your new class.

 
$person = new my_first_class();
var_dump( $person->is_granted() );
$person->first_name = 'George';
$person->grant();
var_dump( $person->is_granted() );
var_dump( $person->first_name );
 

Now have some fun with the concepts and see what you can make your object do!

Comments

Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up