php 中this关键字 :: 符号 magic method

本文介绍了PHP中静态成员的使用方法,包括静态变量和静态方法的调用,并通过示例展示了如何在子类中调用父类的方法。此外,还讲解了PHP中的魔术方法,如构造函数和析构函数等。

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

我们都知道在php或是其他语言中this就是指当前对象本身,我们可以方便的引用自身的一些属性 方法,

有时,在没有声明任何实例的情况下访问类中的函数或者基类中的函数和变量很有用处。而 :: 运算符即用于此情况。

class A {
	static $j='who are you';//如何访问静态变量,	A::$j可以访问,
    function example() {
        echo "I am the original function A::example().<br />\n";
    }
}

class B extends A {
    function example() {
        echo "I am the redefined function B::example().<br />\n";
        A::example();//调用父类的方法,
    }
}

// A 类没有对象,这将输出
//   I am the original function A::example().<br />
A::example();//因为没有实例对象我们只能按类的本身来调用了,
// 建立一个 B 类的对象
$b = new B;
echo A::$j;//输出 who are you
// 这将输出
//   I am the redefined function B::example().<br />
//   I am the original function A::example().<br />
$b->example();

另外,如果从类的内部访问const或者static变量或者方法,那么就必须使用自引用的self,反之如果从类的内部访问不为const或者static变量或者方法,那么就必须使用自引用的$this。

The function names __construct, __destruct (see Constructors and Destructors), __call, __get, __set, __isset, __unset (see Overloading), __sleep, __wakeup, __toString, __clone and __autoload are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.这些方法都是php中的魔术方法,你不能写这样的名字在你的函数内除非你想用这些函数,下面就看看这些函数的基本用法,

class TestClass
{
    public $foo;
	public static $aa = 'aaa';
  
    public function __construct($foo) {//构造函数
        $this->foo = $foo;

    }

    public function __toString() {//析构函数
        return $this->foo;
    }
}

$class = new TestClass('Hello');
echo $class;//输出Hello
//echo TestClass::foo;非静态常量不能用::输出
echo TestClass::$aa;//输出要用$aa
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值