Prev | Current Page 36 | Next

Hasin Hayder

"Object-Oriented Programming with PHP5"

To test this, let's add the following code in our
factorial class:
function __destruct()
{
echo " Object Destroyed.";
}
Now execute the usage script again, you will see the following output this time:
__construct() executed. Factorial of 5 is 120. Object Destroyed.
Class Constants
Hopefully, you will already know that you can create constants in your PHP scripts
using the define keyword to define (constant name, constant value). But to create
constants in the class you have to use the const keyword. These constants actually
work like static variables, the only difference is that they are read-only. Let's see how
we can create constants and use them:
class WordCounter
{
const ASC=1; //you need not use $ sign before Constants
const DESC=2;
private $words;
function __construct($filename)
{
$file_content = file_get_contents($filename);
$this->words =
(array_count_values(str_word_count(strtolower
($file_content),1)));
Chapter 2
[ 27 ]
}
public function count($order)
{
if ($order==self::ASC)
asort($this->words);
else if($order==self::DESC)
arsort($this->words);
foreach ($this->words as $key=>$val)
echo $key ." = ". $val."
";
}
}
?>
This WordCounter class counts the frequency of words in any given file.


Pages:
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48