Extending a Class in OOPHP

Hello Readers

Lest go to check, how to extend a class in Object Oriented PHP. It’ s very easy to make. One of the greatest features in OOP is that you can extend a class and create a completely new object. The new object can retain all the functionality of the parent object from which it is extended or can override. The new object can also introduce some features. Let’s extend our myClass class and override the myNewClass function so that it can send HTML mails.

First of all, create a file named class.extend.php and write these code into this file.

<?php
class myClass{
 public $name;
 public $address;
 
 public function myName($name, $address){
 echo $this->name = $name."<br>";
 echo $this->address=$address."<br>";
 } 
}

class myNewClass extends myClass {
 private $age;
 
 public function myProfile($a, $b, $age)
 {
 $this->myName($a, $b);
 echo $this->age=$age;
 
 }
}

 

//creating a object 
$user= new myNewClass();
$user->myProfile('Suchi', 'Uttara', 23);
?>

 

 

Thanks to read. Take Care.

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.