Documente Academic
Documente Profesional
Documente Cultură
Creating Classes
PHP's support for OOP was limited; however, PHP 5.0 introduced a new object model that allowed programmers
significantly greater flexibility and ease of use when working with classes and objects.
// class definition
// methods
}
}
Once a class has been defined, objects can be created from the class with the new keyword. Class methods and
properties can directly be accessed through this object instance.
Here's an example, which creates an instance of the Automobile class and assigns it to $car, and then sets the
object's properties and invokes object methods (note the -> symbol used to connect objects to their properties or
methods):
<?php
// instantiate object
$car = new Automobile;
// set object properties
$car->color = 'red';
$car->make = 'Ford Taurus';
// invoke object methods
$car->accelerate();
$car->turn();
?>
To access or change a class method or property from within the class itself, it's necessary to prefix the
corresponding method or property name with $this, which refers to "this" class. To see how this works, consider this
revision of the preceding example, which sets a class property named $speed and then modifies this property from
within the accelerate () and brake () functions:
<?php
class Automobile
{
public $color; public $make; public
$speed = 55;
public function accelerate()
{
$this->speed += 10;
echo 'Accelerating to ' . $this->speed . '...';
}
public function brake()
{
$this->speed -= 10;
echo 'Slowing down to ' . $this->speed . '...';
}