Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

PHP Development Part 3 – Objects

Tuesday, February 7th, 2012 by Servage

Hi again, and welcome to this third little guide on PHP development. In this article you’ll learn about the PHP class, which is an object-model for handling various kinds of data. As usual, it’s easiest to understand based on an example. Say, you want to make a web app that has different kinds of users, so we need a User class to handle the user in your scripts.

class User {

	var $first_name;
	var $last_name;
	var $nickname;

	function __constrcut($nickname) {
		$this->nickname = $nickname;

	function get_full_name() {
		return $first_name.' '.$last_name;


The class definition lets PHP know we create a class, containing multiple variables and functions. Classes are also often called objects, and functions inside classes may be called methods. You can create an instance of a class by using the keyword “new”. This will run the __construct() method, whereafter you can perform actions on your object. You can change variables inside the class (variables also called attributes), and run functions/methods.

$my_user = new User('crazyNickName');
echo $my_user->nickname;

$my_user->first_name = 'John';
$my_user->last_name = 'Doe';
echo $my_user->get_full_name();

The above example create a new user. Because of the way we defined the __construct() method in the class, it automatically defines the user nickname, which we echo on the screen. Thereafter we define the first and last name, which we display with out get_full_name() method.

This is the basic way of handling classes. The advantages are that you can create a set of variables and functions that are attached to every object of the class type. So every user gets the same functionality in a clean way, without spaghetti-code. In a future article we will take this concept further.

PHP Development Part 3 - Objects, 3.5 out of 5 based on 2 ratings
Categories: Guides & Tutorials


You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.