Heim  >  Artikel  >  Backend-Entwicklung  >  PHP静态方法和属性

PHP静态方法和属性

WBOY
WBOYOriginal
2016-08-08 09:32:22913Durchsuche
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

从上例看出,使用了static和不适用static属性以后都可以直接使用::方法从外面直接调用。但是为了效率和其他方面因素,还是建议使用static来限制。

static类内部调用方法

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

使用了static关键字来限制的方法必须使用self::在本类内部引用。

static属性

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

static继承与使用

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的继承与普通类的继承方法一样,并没有太大区别。

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

只是使用的时候有写区别,必须是parent::方法来引用父类的方法,并且不能直接self::来使用的方法,不然不会有输出:

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

以上就介绍了PHP静态方法和属性,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn