pTutorial

New way to learn PHP

PHP 5 Static Method

Static method

Static method works same as a static property. You can create a static method by using the static keyword before the function keyword. Static methods are also part of the class but not bound with any object. Therefore $this is not accessible in a static method. Self keyword is used to access the data member.

PHP 5 static method

class MyClass 
{ 
public static function staticMethod() 
{ 
// (do stuff here) 
} 
} 
.

To access a static method, write the class name, followed by two colons, followed by the method name.


MyClass::staticMethod();

Example of static method

<?php

class Student 
{
public $name;

public static function  display()
{

echo "John";

}

}

Student::display();

?>

Output

John

In the Computer class, display is a static method or function which print "John". You can easily call the display method by the class name as shown above.

Download Source script


PHP5 Static method example

Static methods are also part of the class, but not bound with any object. Therefore $this is not accessible in a static method. self keyword is used to access the static data member of the class.

<?php

class Student 
{
public static $name="John";

public static function  display()
{
echo "Name of Student:";

echo self::$name;
}

}

Student::display();

?>

Output

Name of Student:John

Download Source static


Access static property using object

You can also call static method with the help of the object also, but $this would not use in called method.

Static method example

<?php

class Student 
{
public static $name="John";

public static function  display()
{

echo "Name of Student:";

echo self::$name;

}

}
$a=new Student();

$a->display();

?>

Output

Name of Student:John

In the student class, display is a static method and name is the static property. Accessed with the $a object.

Download Source script


QUOTES OF THE DAY

Beauty's tears are lovelies than her smiles.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER