kidys 发表于 2017-4-9 09:02:21

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

  我们都知道在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
 
页: [1]
查看完整版本: php 中this关键字 :: 符号 magic method