Wednesday, December 9, 2009

Static modifier use in php

Static method doesn't require an instance (and may return one instead) and is more or less like a global function except for it is put in class' namespace (and therefore avoid collisions with other functions) and has access to class' private members.

So, use it whenever you're interested in these properties of the function.

class Student{
static $total_students=0;

static public function add_student(){
Student::$total_students++;
}

static function welcome_students($var="Hello"){
echo "{$var} students";
}
}

echo Student::$total_students;
echo "
";
echo Student::welcome_students();
echo "
";
echo Student::welcome_students("Welcome");
echo "
";
Student::$total_students=3;
echo Student::$total_students;
echo "
";
Student::$total_students=1;
echo Student::$total_students;
echo "
";

////Static variable shared through the inherited tree

class One{
static $foo;
}
class Two extends One{

}
class Three extends One{

}

One::$foo=1;
Two::$foo=2;
Three::$foo=3;
echo One::$foo;
echo "
";
echo Two::$foo;
echo "
";
echo Three::$foo;
?>

source:lynda.com and stackoverflow.com

No comments:

Post a Comment

I just got my #domain @BigRock. Get upto 25% off with my personalized coupon link Get upto 25% off