PHP Static keyword

Source: Internet
Author: User
Static keyword

Declaring a class member or method as static can be accessed directly without instantiating the class. Static members cannot be accessed through an object (except static methods).

To be compatible with PHP4, if no visibility is specified, the properties and methods default to public.

Because static methods do not need to be called through an object, the pseudo-variable $this is not available in a static method.

A static property cannot be accessed by an object through the operator.

Using:: Calling a non-static method will result in an e_strict level error.

Just like all other PHP static variables, a static property can only be initialized to a character value or a constant and cannot use an expression. So you can initialize a static property to an integer or an array, but you can't point to another variable or function return value, or point to an object.

After PHP5.3.0, we can use a variable to invoke the class dynamically. However, the value of the variable cannot be the keyword self, parent, or static.

Example #1 static Member code example

Class Foo
{
public static $my _static = ' foo ';

Public Function Staticvalue () {
Return self:: $my _static;
}
}

Class Bar extends Foo
{
Public Function foostatic () {
Return Parent:: $my _static;
}
}


Print Foo:: $my _static. " ";

$foo = new Foo ();
Print $foo->staticvalue (). " ";
Print $foo->my_static. " "; Undefined "Property" My_static

Print $foo:: $my _static. " ";
$classname = ' Foo ';
Print $classname:: $my _static. " "; PHP 5.3.0 can be dynamically called after

Print Bar:: $my _static. " ";
$bar = new Bar ();
Print $bar->foostatic (). " ";
?>

Example #2 static Method code example

Class Foo {
public static function Astaticmethod () {
// ...
}
}

Foo::astaticmethod ();
$classname = ' Foo ';
$classname:: Astaticmethod (); As of PHP 5.3.0
?>

Source: http://www.php100.com/cover/php/83.html

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.