PHP Static modifiers

<?php

// static modifier

// with static methods you can't use $this


// this : talking about current instance
// self : talking about current class


class Student{

static $total_students = 6;


static public function add_students()
{
//here you can use either Student or self.
//but self is better because it's inside the Student class.
self::$total_students++;// self : talking about current class.
}

static function welcome_students($var="Hello")
{
echo "{$var} students";
}
}
//$student = new Student();
//$student-> total_students; // <- instance call

echo Student::$total_students."
"; // <- static call
echo Student::welcome_students("Good bye")."
";
echo Student::add_students()."
";

//Student::$total_students = 1;
echo Student::$total_students."
";


/* -------- VERY IMPORTANT ----------
* static variables are shared throughout the inheritance tree
* even if you assign different values inside child classes, it's taken value
* of parent class.
*/

class One{
static $foo;
}

class Two extends One{ }
class Three extends Two{}

One::$foo = 1;
Two::$foo = 2;
Three::$foo = 3;


echo One::$foo."
";
echo Two::$foo."
";
echo Three::$foo."
";



?>

Comments

Popular posts from this blog

IrfanView : Simple Windows graphic viewer

MySQL Cluster Overview