Documente Academic
Documente Profesional
Documente Cultură
A destructor function cleans up any resources allocated to an object once the object is
destroyed.
<?php
class MyClass {
// Constructor
public function __construct(){
echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}
// Destructor
public function __destruct(){
echo 'The class "' . __CLASS__ . '" was destroyed.<br>';
} }
// Create a new object
$obj = new MyClass;
// Output a message at the end of the file
echo "The end of the file is reached.";
?>
The PHP code in the above example will produce the following output:
A destructor is called automatically when a scripts ends. However, to explicitly trigger the
destructor, you can destroy the object using the PHP unset() function, as follow:
<?php
class MyClass {
// Constructor
public function __construct(){
echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}
// Destructor
public function __destruct(){
echo 'The class "' . __CLASS__ . '" was destroyed.<br>';
}
}
// Create a new object
$obj = new MyClass;
// Destroy the object
unset($obj);
// Output a message at the end of the file
echo "The end of the file is reached.";
?>
Now, the PHP code in the above example will produce the following output:
Tip: PHP automatically clean up all resources allocated during execution when the script is
finished, e.g. closing database connections, destroying objects, etc.
Note: The __CLASS__ is a magic constant which contains the name of the class in which it
is occur. It is empty, if it occurs outside of the class.
Lecture 22 Web Systems and Technologies
public — A public property or method can be accessed anywhere, from within the class
and outside. This is the default visibility for all class members in PHP.
protected — A protected property or method can only be accessed from within the class
itself or in child or inherited classes i.e. classes that extends that class.
private — A private property or method is accessible only from within the class that
defines it. Even child or inherited classes cannot access private properties or methods.
The following example will show you how this visibility actually works:
In the following example we have added three different access modifiers to the three
properties. Here, if you try to set the name property it will work fine (because the name
property is public). However, if you try to set the color or weight property it will result in a
fatal error (because the color and weight property are protected and private):
<?php
class Fruit {
public $name;
protected $color;
private $weight;
}
In the next example we have added access modifiers to two methods. Here, if you try to call
the set_color() or the set_weight() function it will result in a fatal error (because the two
functions are considered protected and private), even if all the properties are public:
Example
<?php
class Fruit {
public $name;
public $color;
public $weight;