Programming Tutorials

Objects in PHP

By: Andi, Stig and Derick in PHP Tutorials on 2008-11-22  

The main difference in OOP as opposed to functional programming is that the data and code are bundled together into one entity, which is known as an object. Object-oriented applications are usually split up into a number of objects that interact with each other. Each object is usually an entity of the problem, which is self-contained and has a bunch of properties and methods. The properties are the object's data, which basically means the variables that belong to the object. The methods -if you are coming from a functional background -are basically the functions that the object supports. Going one step further, the functionality that is intended for other objects to be accessed and used during interaction is called an object's interface.

A class is a template for an object and describes what methods and properties an object of this type will have. In this example, the class represents a person. For each person in your application, you can make a separate instance of this class that represents the person's information. For example, if two people in our application are called Joe and Judy, we would create two separate instances of this class and would call the setName() method of each with their names to initialize the variable holding the person's name, $name. The methods and members that other interacting objects may use are a class's contract. In this example, the person's contracts to the outside world are the two set and get methods, setName() and getName().

The following PHP code defines the class, creates two instances of it, sets the name of each instance appropriately, and prints the names:

class Person {
	private $name;
	function setName($name)
	{
		$this->name = $name;
	}
	function getName()
	{
		return $this->name;
	}
};
$judy = new Person();
$judy->setName("Judy");
$joe = new Person();
$joe->setName("Joe");
print $judy->getName() . "\n";
print $joe->getName(). "\n";





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

Objects in PHP

Booleans in PHP

PHP pages does not display in IIS 6 with Windows 2003

Installing PHP with Apache 2.x on HP UX 11i and configuring PHP with Oracle 9i

Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Installing PHP with nginx-server under windows

Warning: session_start(): open .... failed - PHP error

Floating point precision in PHP

Function to return number of digits of an integer in PHP

Convert IP address to integer and back to IP address in PHP

Function to force strict boolean values in PHP

Convert a hex string into a 32-bit IEEE 754 float number in PHP

Latest Articles (in PHP)