Home  >  Article  >  Backend Development  >  PHP static methods and properties

PHP static methods and properties

WBOY
WBOYOriginal
2016-08-08 09:32:22918browse
class hw
{
	public static function hi()
	{
		return 'Hello World';
	}
}
echo hw::hi();//Output:Hellp World

class hw2
{
	public function hi()
	{
		return 'Hello Wrold';
	}
}
echo hw2::hi();//Output:Hellp World

As can be seen from the above example, after using the static attribute or not using the static attribute, you can directly use the :: method to call it directly from the outside. However, for efficiency and other reasons, it is recommended to use static restrictions.

Calling methods within a static class

class foo
{
    private static function c()
    {
        return 'abcde';
    }

    public static function a()
    {
        echo self::c();
    }

    public static function b()
    {
        echo $this->c();
    }

    public function  e()
    {
        echo self::c();
    }
}
foo::a();//Output:abcde
foo::b();//Output:Fatal error: Using $this when not in object context in
foo::e();//Output:abcef

Methods restricted using the static keyword must be referenced within this class using self::.

static attribute

class foo
{
	public static $a;
	public static function a()
	{
		self::$a = 'abcd';
	}
}
foo::a();//Output:abcde
echo foo::$a;

static inheritance and use

class foo
{
	public static $a;
	public static function a()
	{
		return 'abcde';
	}
}

class soo extends foo
{
	public static function a()
	{
		echo '12345';
	}
}

soo::a();//Output:12345
static inheritance is the same as the inheritance method of ordinary classes, and there is not much difference.

class foo
{
	public static $a;
	public static function a()
	{
		return 'abcde';
	}
}

class soo extends foo
{
	public static function a()
	{
		echo parent::a();
	}
}

soo::a();//Output:12345

There is only a writing difference when using it. It must be the parent:: method to reference the method of the parent class, and the method cannot be used directly by self::, otherwise there will be no output:

class foo
{
	public static $a;
	public static function a()
	{
		return 'abcd';
	}
}
 
class soo extends foo
{
	public static  function aa()
	{
		echo self::a();
	}
}
soo::a();  

The above introduces PHP static methods and attributes, including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn