php的scope是什么意思,PHP之 范围解析操作符Scope Resolution Operator (::)

本文介绍了PHP中的Scope Resolution Operator(也称为Paamayim Nekudotayim),即双冒号运算符,用于访问类的静态属性、常量和覆盖的方法。从类外部访问时,使用类名;从内部访问时,可以使用self, parent和static关键字。通过示例展示了如何从类内部和外部使用该运算符,以及如何调用父类的方法。此外,还讨论了如何在子类中重写方法但仍然调用父类方法的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The Scope Resolution Operator (also

called Paamayim Nekudotayim) or in simpler terms, the double colon,

is a token that allows access to static, constant, and overridden

properties or methods of a class.

When referencing these items from

outside the class definition, use the name of the class.

As of PHP 5.3.0, it's possible to

reference the class using a variable. The variable's value can not

be a keyword (e.g. self, parent and static).

Paamayim Nekudotayim would, at

first, seem like a strange choice for naming a double-colon.

However, while writing the Zend Engine 0.5 (which powers PHP 3),

that's what the Zend team decided to call it. It actually does mean

double-colon - in Hebrew!

Example #1 :: from outside the class

definition

class MyClass {

const CONST_VALUE = 'A constant

value';

}

$classname = 'MyClass';

echo $classname::CONST_VALUE; // As

of PHP 5.3.0

echo MyClass::CONST_VALUE;

?>

Three special keywords self, parent

and static are used to access properties or methods from inside the

class definition.

Example #2 :: from inside the class

definition

class OtherClass extends

MyClass

{

public static $my_static = 'static

var';

public static function doubleColon()

{

echo parent::CONST_VALUE .

"\n";

echo self::$my_static . "\n";

}

}

$classname = 'OtherClass';

echo $classname::doubleColon(); //

As of PHP 5.3.0

OtherClass::doubleColon();

?>

When an extending class overrides

the parents definition of a method, PHP will not call the parent's

method. It's up to the extended class on whether or not the

parent's method is called. This also applies to Constructors and

Destructors, Overloading, and Magic method definitions.

Example #3 Calling a parent's

method

class MyClass

{

protected function myFunc() {

echo "MyClass::myFunc()\n";

}

}

class OtherClass extends

MyClass

{

// Override parent's

definition

public function myFunc()

{

// But still call the parent

function

parent::myFunc();

echo "OtherClass::myFunc()\n";

}

}

$class = new OtherClass();

$class-&gtmyFunc();

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值