The Basicsclass
Every class definition begins with the keyword class, followed by a class
name, which can be any name that isn't a reserved
word in PHP. Followed by a pair of curly braces,
which contains the definition of the classes members and methods. A
pseudo-variable, $this is available when a method is
called from within an object context. $this is a
reference to the calling object (usually the object to which the method
belongs, but can be another object, if the method is called
statically from the context
of a secondary object). This is illustrated in the following examples:
$this variable in object-oriented language
foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>
]]>
&example.outputs;
Simple Class definition
var;
}
}
?>
]]>
The default value must be a constant expression, not (for example) a
variable, a class member or a function call.
Class members' default value
]]>
There are some nice functions to handle classes and objects. You might want
to take a look at the Class/Object
Functions.
new
To create an instance of a class, a new object must be created and
assigned to a variable. An object will always be assigned when
creating a new object unless the object has a
constructor defined that throws an
exception on error. Classes
should be defined before instantiation (and in some cases this is a
requirement).
Creating an instance
]]>
In the class context, it is possible to create a new object by
new self and new parent.
When assigning an already created instance of a class to a new variable, the new variable
will access the same instance as the object that was assigned. This
behaviour is the same when passing instances to a function. A copy
of an already created object can be made by
cloning it.
Object Assignment
var = '$assigned will have this value';
$instance = null; // $instance and $reference become null
var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>
]]>
&example.outputs;
string(30) "$assigned will have this value"
}
]]>
extends
A class can inherit methods and members of another class by using the
extends keyword in the declaration. It is not possible to extend multiple
classes, a class can only inherit one base class.
The inherited methods and members can be overridden, unless the parent
class has defined a method as final,
by redeclaring them with the same name defined in the parent class.
It is possible to access the overridden methods or static members by
referencing them with parent::
Simple Class Inheritance
displayVar();
?>
]]>
&example.outputs;