PHP Classes

Object Oriented PHP Programming

If you read the last tutorial on there, you might be wondering why your code isn’t working. You entered everything there, but at best, you’re getting only a white screen. Well, that’s because I showed you pseudocode; those Classes don’t actually exist, so we need to write them.

Person Class

class Person{
	
	private $first_name;
	private $last_name;
	private $position;
	private $age;
	
	private $my_pencil = null;
	
	public function __construct( $fname, $lname, $position, $age ){
		$this->first_name = $fname;
		$this->last_name = $lname;
		$this->position = $position;
		$this->age = $age;
	}
	
	public function GivePencil( Pencil $pencil ){
		$this->my_pencil = $pencil;
	}
	
	public function BreakPencil(){
		unset($this->my_pencil);
		$this->my_pencil = null;
	}
	
	public function WriteText( $text ){
		if( ! is_null($this->my_pencil) ){
			
			$this->my_pencil->Write( $text );
			
		}
	}
	
	public function EraseAllText(  ){
		if( ! is_null($this->my_pencil) ){
			
			$this->my_pencil->EraseAll(  );
			
		}
	}
	
}

Pencil Class

class Pencil{
	
	private $weight;
	private $length;
	private $percent_eraser_left;
	
	public function __construct( $weight, $length, $percent_left ){
		$this->weight = $weight;
		$this->length = $length;
		$this->percent_eraser_left = $percent_left;
	}
	
	public function Write( $text ){
		echo $text;
	}
	
	public function EraseAll(){
		// should find some way to erase all text. 
	}
	
}

Now that we have those class definitions, we can instantiate those classes; these instantiations are known as objects.

The first thing you’ll notice about the syntax is the class Keyword. This informs the PHP parser that we’re providing a definition of what is Type Person and Type Pencil. We follow the class keyword with the name of the class, with a matching set of curly braces.

Access Specifiers

One key concept of Object Oriented PHP Programming is hiding data and functions that those outside the class don’t need to know about. This is accomplished with our Access Specifiers, Public, Private and Protected.

I don’t use Protected very often, so I’m not going to cover it in depth, but I do use Public and Private.

Public

An Access Specifier telling the PHP parser that this property or method is accessable outside the class definition.

Private

An Access Specifier telling the PHP parser that this property or method is inaccessable outside the class definition.

Protected

An Access Specifier telling the PHP parser that this property or method is accessable only to this class and related classes.

By using these specifiers, we can limit what can be directly changed or used within the class. These provides some means of data validation by forcing data access to go through Accessors and Mutators

Accessors and Mutators

Though we haven’t added any Accessors or Mutators to our class, we can easily do this. Let’s revisit our class declaration:

class Person{
	
	private $first_name;
	private $last_name;
	private $position;
	private $age;
	
	private $my_pencil = null;
	
	// These are our new Accessors and Mutators
	public function GetFirstName(){return $this->first_name;}
	public function SetFirstName($name){$this->first_name = $name;}
	
	public function GetLastName(){return $this->last_name;}
	public function SetLastName($lname){$this->last_name = $lname;}
	
	public function GetPosition(){return $this->position;}
	public function SetPosition($position){$this->position = $position;}
	
	//these Accessor Mutator pair provides data validation
	public function GetAge(){return $this->age;}
	public function SetAge($age){
		if( $age >= 20 ){
			
			if($age < 100){ 				$this->age = $age
			}
			else
			{
				echo "Must Be Less Than 100 To Use This Class!";
			}
			
		}
		else
		{
			echo "Must Be 20 or Older To Use This Class!";
		}
	}
	
	public function __construct( $fname, $lname, $position, $age ){
		$this->first_name = $fname;
		$this->last_name = $lname;
		$this->position = $position;
		$this->age = $age;
	}
	
	...
}

You might be wondering what the point of an Accessor or Mutator is; in short, they are methods that can perform transformations and validations on information passed to and from the object. Because PHP is a dynamically-typed language, you can’t ensure that properties will always be a certain type, as you can in other languages, like C++, so to ensure that a property will always be the right type, you could use a Mutator.

Given the example above, we could have a Mutator for setting the Pencil that a Person can use. Let’s add a Accessor/Mutator pair for the $my_pencil property.

...
    // Allows us to make sure that a Pencil always exists
    public function GetMyPencil()
    {
        if( is_null($this->my_pencil) )
        {
            $p = new Pencil();
            $this->setMyPencil($p);
        }


        return $this->my_pencil;
    }

    // enforces $newPencil to be of type Pencil, so $my_pencil can't be anything other than Pencil
    public function SetMyPencil(Pencil $newPencil)
    {
        $this->my_pencil = $newPencil;
        return $this;
    }
}

The example above shows you how you can ensure type validation in classes.

Stay tuned for more posts on Object Oriented PHP Programming!

Facebooktwitterredditpinterestlinkedinmail

2 thoughts on “PHP Classes

  1. I am really inspired by your writing talents,
    as well as with the format on your blog. Is this a paid subject or did you modify it your
    self? Either way, keep up the nice, high quality writing; it’s rare to find a nice weblog like this
    one nowadays..

Leave a Reply

Your email address will not be published. Required fields are marked *

Thanks for your thoughts!

*