This tutorial will relate to objects in PHP 4.
Creating classes
The example below shows the basic syntax for an object.
class MyClass
{
var $field1;
//Constructor
function MyClass($arg1)
{
$this->field1 = $arg1;
}
function myMethod()
{
//Object function
return $this->field1;
}
}
The first thing to note is the keyword class followed by the class name. Fields in objects are deonted by the var keyword and are referenced in the class by the $this variable.
Inheritance
Inheritance in PHP is implemented using the extends keyword.
class MyClass2 extends MyClass
{
var $field2;
function MyClass2($arg1)
{
//Parent constructor
parent::MyClass();
$this->field2 = $arg1;
}
function myMethod2()
{
//Call a function from the parent
parent::myMethod();
}
}
When extending an object the parents constructor is not automatically called this must be done using the parent:: command which refers to the parent class.
Static methods
If a class has static methods they can be called using the scope resolution operator.
class Math
{
function GoldenRatio()
{
return ((1.0 + sqrt(5)) / 2.0);
}
}
echo Math::GoldenRatio();
This class has a single method that returns a constant, it does not need to be instantiated to use the method so the :: operator was used to call the method.
Instantiating a class and calling methods
The code below creates an object from the class defined above.
$object = newMyClass(5); echo $object->myMethod(); //Returns 5
In PHP the fields can be accessed directly.
$object = newMyClass(5); echo $object->field1; //Returns 5
MySQL is a registered trademark of MySQL AB in the United States, the European Union and other countries.