Actually there is no chance of executing both. If there is a constructor in both styles,
PHP5 will give preference to the __construct() function and the other one will be
ignored. Let's take a look using the following example
//class.factorial.php
class Factorial
{
private $result = 1;
private $number;
function __construct($number)
{
$this->number = $number;
for($i=2; $i<=$number; $i++)
{
$this->result*=$i;
}
echo "__construct() executed. ";
}
function factorial($number)
{
$this->number = $number;
for($i=2; $i<=$number; $i++)
{
$this->result*=$i;
}
echo "factorial() executed. ";
}
public function showResult()
{
echo "Factorial of {$this->number} is {$this->result}. ";
}
}
?>
Kick-Starting OOP
[ 26 ]
Now if you use this class as shown below:
include_once("class.factorial.php");
$fact = new Factorial(5);
$fact->showResult();
?>
You will find that the output is:
__construct() executed. Factorial of 5 is 120
Similar to the constructor method, there is a destructor method which actually works
upon destroying an object. You can explicitly create a destructor method by naming
it __destruct(). This method will be invoked automatically by PHP at the end of
the execution of your script.
Pages:
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47