Word Count in a file by Object Oriented PHP

Hello Readers
Now I am ready to show you, how to make a object oriented PHP program to count the words in a file. Let’s go to start the work.
First of all, you have to create two files called index.php and mywords.php. In index.php file, you have to write the below codes.

<?php

//creating a class
class WordCounter{
const ASC=1;        //this is a constant
const DESC=2;    //this is a constant

private $words;   //called a private variable

function __construct($filename)
{
$file_content=file_get_contents($filename);
$this->words=array_count_values(str_word_count(strtolower($file_content),1));

}

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.”<br>”;
}
}
}
?>
<!DOCTYPE>
<html>

<body>
<?php
$wc=new WordCounter(“myWords.php”);
$wc->count(WordCounter::DESC);

?>
</body>
</html>

Now, go to create a another file named ‘myWords.php‘.
<!DOCTYPE>
<html>
<head>
<title></title>
</head>

<body>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

</body>
</html>

 

Now, run your file in your localhost / web server to show the result.

 

Thanks for reading.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s