Example to use Class, Constructor, Functions and Objects in PHP programs

In this post you are going to learn about the use and the concept of Class, Constructor, Functions and Objects in PHP.

Please find the below example for the same.

 <title>PHP example inside HTML tags</title>
<div style="background: aqua; color: navy; font-family: cursive; font-size: large">
 A simple example page in php : use of class, constructor and methods or functions...
 echo 'Welcome to php';
 // echo is used to displaye string, character, number, etc. in php. We can place the contents inside ' ' or " "
 /* Everything in php is written inside :
 Start:     <?php
End:     ?>
 //class in php is written by using the keyword class followed by class name
 class myfirstphp{
private $result;
//here $result has been declared as private so like other languages it is visible inside the class only
 //$result can store any type of value either it is string, character, integer, decimal, array, etc.
 //to access or store any value to $result we will use $this->result
 //$this-> is used to access methods or any thing dynamically
function __construct(){
 echo 'This is php constructor';
//method or funtion name starts with function then the name of method or funtion
function normal(){
 echo 'this is php function';
 }//end of function normal()
//parametrized function in php
function set($val){
 //this will store the multiplication result in the top most declaration of result variable
 }//end of function set($val)
function get(){
 return $this->result;
}//end of class area
 <div style="font-size: medium; font-family: sans-serif;">
 Object creation in php and call to funtions.<br>
$object=new myfirstphp();
//  $object will hold the ref. of class
 // new is used to create object of class and new myfirstphp(); will result in creation of object and call to constructor
echo '<br>';
//call to method or function normal()
 //for all the dynamic calls we will use $classobject->funcationame()
echo "<br>";
$object->set(20);//argument or parameter passed to function on call
echo '<br>';
echo $object->get();
 *  the above code can be extended in two lines as:
 *  $value=$object->get();
 *  echo $value;
//call in php to dynamic funtion is made by using -> on object.

To Run:
1. Save the file as index.php in a folder name abc
2. Move the folder to the root directory of wamp server i.e. www
3. Start the WAMP Server
4. Open your browser and in url type: localhost/abc and press enter
5. You will find your php page running now.

Best Regards!!!

Related Post


Rohin Saini has written 3 articles