PHP Static Variables with Examples

Program 1

<html>
<head><title>Demo</title></head>
<body>
    <center>
<?php 
     class Myclass
     {
          public static $n=0;

          function __construct()
          {
                ++self::$n;
          }
          function display()
          {
              echo "Total Object: ".self::$n;
              echo "<br>";
          }
     }

     // Create Object
     $M1=new Myclass();   // M1->n=1
     $M2=new Myclass();  // M2->n=1
     $M3=new Myclass();  // M3->n=1

     $M4=new Myclass();   // M1->n=1
     $M5=new Myclass();  // M2->n=1
     $M6=new Myclass();
     $M7=new Myclass();   // M1->n=1
     $M8=new Myclass();  // M2->n=1
     $M9=new Myclass();

     //$M1->display();
    // $M2->display();
     $M3->display();

?>
</center>
</body>
</html>

Program 2

<html>
<head><title>Demo</title></head>
<body>
    <center>
<?php 
     class Student
     {
           public $name;
           public static $clgname="XYZ Indore College";

          function __construct($n)
          {
                $this->name=$n;
               
          }
          function display()
          {
            echo "    Student Name: ".$this->name;
            echo "     College Name: ".self::$clgname;
          }
            static  function  add($a,$b)
          {
               $c=$a+$b;
               echo "Addition is: ".$c;
          }
     }

     echo  Student::$clgname;
        // Student::add(50,20);
    //  $S1=new Student("Rajesh");
    //  $S2=new Student("Anil Sharma");
    //  $S3=new Student("Ritu");
    //  $S1->display();
    //  $S2->display();
    //  $S3->display();
?>
</center>
</body>
</html>

 

courses
Image

TechVidvan Team

TechVidvan Team provides high-quality content & courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.

Leave a Reply

Your email address will not be published. Required fields are marked *