Tuesday, March 31, 2009

Static declaration with example in php

In php, you can declare method or member of a class as static. If you do so then you can access the method/member without creating any instance.

In fact, if you declare a member of a class as static then that member can't be accessed with an instantiated class object. So you would not be able to access a static variable using arrow sign. However static method can be accessed via instantiation.

Another thing about static method is, the pseudo variable $this is not available inside the method declared as static.

Below is an example of static declaration with example in php.

<?php
class StaticExample{
static $staticVariable=10;
static function staticMethod(){
echo "This method is declared as static";
}
}
echo StaticExample::$staticVariable;
echo "<br />";
StaticExample::staticMethod();
echo "<br />";
$staticExampleInstance=new StaticExample();
$staticExampleInstance->staticMethod();
echo "<br />";
echo $staticExampleInstance->staticVariable; //This is undefined, so no output will be displayed.
?>

And in browser the output is,

10
This method is declared as static
This method is declared as static

Related Documents
http://arjudba.blogspot.com/2009/03/class-concepts-and-usage-syntax-in-php.html
http://arjudba.blogspot.com/2009/03/class-inheritance-example-in-php.html
http://arjudba.blogspot.com/2009/03/autoloading-objects-in-php.html
http://arjudba.blogspot.com/2009/03/constructors-and-destructors-in-php.html

No comments:

Post a Comment