扫码一下
查看教程更方便
每个类的定义都以关键字 class 开头,后面跟着类名,后面跟着一对花括号,里面包含有类的属性与方法的定义。
类名可以是任何非 php 保留字 的合法标签。一个合法类名以字母或下划线开头,后面跟着若干字母,数字或下划线。以正则表达式表示为:
^[a-za-z_\x80-\xff][a-za-z0-9_\x80-\xff]*$
一个类可以包含有属于自己的 常量 ,变量 (称为“属性”)以及函数(称为“方法”)。
var;
}
}
?>
当一个方法在类定义内部被调用时,有一个可用的伪变量 $this
。$this
是一个到当前对象的引用。
注意:以静态方式去调用一个静态方法,将会抛出一个 error。 在 php 8.0.0 之前版本中,将会产生一个deprecation警告,同时
$this
将会被声明为未定义。
$this
伪变量的示例foo();
a::foo();
$b = new b();
$b->bar();
b::bar();
?>
以上例程在 php 7 中的输出:
$this is defined (a)
deprecated: non-static method a::foo() should not be called statically in %s on line 27
$this is not defined.
deprecated: non-static method a::foo() should not be called statically in %s on line 20
$this is not defined.
deprecated: non-static method b::bar() should not be called statically in %s on line 32
deprecated: non-static method a::foo() should not be called statically in %s on line 20
$this is not defined.
以上例程在 php 8 中的输出:
$this is defined (a)
fatal error: uncaught error: non-static method a::foo() cannot be called statically in %s :27
stack trace:
#0 {main}
thrown in %s on line 27
要创建一个类的实例,必须使用 new 关键字。当创建新对象时该对象总是被赋值,除非该对象定义了 构造函数 并且在出错时抛出了一个 异常。类应在被实例化之前定义(某些情况下则必须这样)。
如果在 new 之后跟着的是一个包含有类名的字符串 string,则该类的一个实例被创建。如果该类属于一个命名空间,则必须使用其完整名称。
注意: 如果没有参数要传递给类的构造函数,类名后的括号则可以省略掉。
在类定义内部,可以用 new self 和 new parent 创建新对象。
当把一个对象已经创建的实例赋给一个新变量时,新变量会访问同一个实例,就和用该对象赋值一样。此行为和给函数传递入实例时一样。可以用 clone 给一个已创建的对象建立一个新实例。
有几种方法可以创建一个对象的实例。
以上例程会输出:
bool(true)
bool(true)
bool(true)
上面示例涉及到的一些新的知识点 例如 在后面章节会介绍。