Example to use Class, Constructor, Function and Object in PHP programs

This is a simple step taken to show the use the concept of classes, constructor, functions or methods, object in php. Please refer to our page section “PHP Introduction” if you are having the first class in PHP or you are writing first Program in PHP

PHP example inside HTML tags


        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 :
       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

  Object creation in php and call to funtions.


  $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 ‘
//call to method or function normal()
//for all the dynamic calls we will use $classobject->funcationame()


  echo “
$object->set(20);//argument or parameter passed to function on call

  echo ‘

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 XYZ
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/xyz and press enter
5. You will find your php page running now. 

Best of Luck!!!

Leave a Reply

Contact Us
close slider
Contact Us

How can we help you with?