Skip to content

An Introduction to PHP Classes

by Rokan on August 8th, 2009

About Object-Oriented Programming

Many programming languages are object-oriented. However, the method of defining an object varies from language to language. Some examples of object-oriented languages are:

  • Java
  • JavaScript
  • C++
  • and finally, PHP

Basic Class Programming in PHP

In PHP, an object is defined as this:

class myObject {
    //variables and methods go here
}

Methods are easy to add to classes. If you wanted to add a function to myObject that returns the current server time, you could do this:

class myObject{
	function getServerTime() {
		return time();
	}
}

Easy as that. Defining variables is a little bit trickier. There are many ways to define variables, but we’ll keep it simple for now and use the ‘var’ method.

class myObject {
        //this is a valid assignment
	var $variable     = 'constant value';

        //this is invalid because it is assigning to a function. This can't be done.
	var $serverTime = time();
}

To access internal variables, we have to use the $this variable. $this is a pointer that points internally, so that we can access the variables we just declared. So, we’re going to add a function to ‘myObject’ and access $variable.

class myObject {
        //this is a valid assignment
	var $variable     = 'Hello World!';
	function GetVariable() {
		//notice how there is no dollar sign $ in front of the variable
		return $this->variable; //this will return 'Hello World!'
	}
}

Notice how there is no dollar sign ($) in front of the variable we are pointing to with $this. This is also how you call methods internally.

On the last note of basic PHP classes, you will need to know how to create an instance of your class. Once you have created an instance of your class, you can use it in the same way you used ‘this’. To create an instance, use the method:

$instance = new ClassName();

This creates a new instance of the class ‘ClassName’. So, an example using everything we’ve learned:

class myClass {
	var $string = 'Hello World!';
	function ShowString() {
		echo $this->string;
	}
}
$instance = new myClass();
$instance->ShowString();

Also, it is entirely possible to create an instance of a class from a string:
class MyClass { function Exist() { echo "My class name is ".get_class($this).""; } } $classname = 'MyClass'; $instance = new $classname(); $instance->Exist(); //this will echo 'My class name is MyClass' That’s about it on a basic level! Now for some more advanced usage of classes.

Advanced Classes

Now that you know how to use variables, it’s time to learn about private and public variables. Basically, a private variable can only be accessed internally by the class itself; and a public variable can be accessed by everything. A variable you would want to keep private could be the password of a user class, for example. A public variable could be the title of the page. Public and private variables are very useful. Here is a class that uses public and private variables:
class myClass {
	private $private_var = "This variable is private! You can't see this!";
	public  $public_var  = "This variable is public! Anyone can see this!";

	//note- you can also use public and private modifiers on functions
	//this is useful because internal functions should be private
	//and external functions could use more than one private function
	//it's good to make a network of public and private methods and variables
	public function PrintPrivate() {
		var_dump($this->private_var);
	}
}
$instance = new myClass();

//this line will print the contents of $private_var to the screen
//because it is being called internally using an external function of myClass
$instance->PrintPrivate();

//however, this line will print an error - private variables can't be accessed
//this is because it is being accessed externally
var_dump($instance->private_var);

When an instance of a class is created, the method (if it exists) $instance->__construct(arguments). So, with this knowledge, you should have realised that when calling:$instance = new myClass(arguments) the arguments are sent to the method __contruct inside myClass. This method is called a constructor. When an instance is deleted, the class destructor is called. The destructor is called when either every variable inside the class has been removed using the PHP function unset($variable) or at the end of the script.

class myClass {
	public $id;
	public function __construct($id) {
		$this->id = $id;
		echo "Constructed {$this->id}
";
	}
	public function __destruct() {
		echo "Destructed {$this->id}
";
	}
}

$count = 0;
$instance = Array();

//this line calls the 'construct' method and creates a new instance
$instance[$count] = new myClass($count);
$count ++;

$instance[$count] = new myClass($count); $count ++;
$instance[$count] = new myClass($count); $count ++;

This code will echo:

Constructed 0
Constructed 1
Constructed 2
Destructed 0
Destructed 1
Destructed 2

You can see that the constructor is called when the instance is created, and that the destructor is called when the script ends.

Now that we understand all of that, we can move on to…

Static Classes

So far, the classes have held variables, and have been individual instances. However, if, for example, you wanted a variable that had a set value and applied to all instances of the class, how would you do it? The answer is static variables:

class myClass {

 //the use of 'static' can be before or after 'public'
 //and it makes the variable global across the class
 static public $variable = 'Hello World!<br/>';

 static public function ShowText() {
 //for static variables, we use self:: instead of $this->
 echo self::$variable;
 }

 //notice that there is no constructor

}

//there is no need to construct a static class!
myClass::ShowText();
//this will output 'Hello World!'

//however, it is possible to create instances and use static at the same time
$class = Array();
$class[0] = new myClass();

//this is an invalid static function caller:
//$class[0]::ShowText();
//this will result in a parse error!

//this will work:
$class[0]->ShowText();
//it works because the function can be accessed
//statically and non-statically

$class[1] = new myClass();

//let's try something!
var_dump($class[0]->variable); echo "<br/>";
var_dump($class[1]->variable); echo "<br/>";
//these will both echo NULL because using ->
//as a pointer is incorrect!

$class[0]->variable = 'I\'m class one!';
$class[1]->variable = 'I\'m class two!';

$class[0]->ShowText();
$class[1]->ShowText();
//these will both echo 'Hello World!' because
//using -> as an operator will only change
//the class instance value of $variable
//which previously didn't exist.

//let's try changing it statically and echoing again!
myClass::$variable = 'This text has been changed!<br/>';
$class[0]->ShowText();
$class[1]->ShowText();
//these will both echo 'This text has been changed!' because
//the variable has statically been changed
//and this applies to all instances of the class

From → PHP Tutorials

2 Comments
  1. dan permalink

    Nice tutorial, but I think you’ve made a mistake in the page’s coding.. because the tutorial doesn’t look like it’s displayed properly. Everything is in a big scroll box. But otherwise nice tut.

  2. dan permalink

    Figured it out… just before ‘Advanced Classes’, you didn’t close a ‘pre’ section. It then wraps the rest of the tutorial in a code like box..
    Hope that helps.

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS