当前位置:网站首页>PHP类与对象详细介绍
PHP类与对象详细介绍
2022-06-21 08:00:00 【旋风1+1】
基本概念
class
每个类的定义都以关键字class开头,后面跟着类名,类名后面跟着一对花括号,里面包含有类的属性与方法的定义。
类名可以是任何非PHP保留字的合法标签。一个合法类型以字母或下划线开头(但不能一数字开头),后面跟着若干字母、数字、下划线。以正则表达式为:[a-zA-Z_][a-zA-Z0-9]*。
一个类可以包含有属于自己的常量、变量(成为“属性”)以及函数(成为“方法”)。
Example # 1简单的类定义:
<?php
class SimpleClass{
// 声明属性
public $var = 'a default value';
// 声明属性
public function desplayVar(){
echo $this->var;
}
}
?>当一个方法在类内部定义被调用时,有一个可以用的伪变量$this。$this代表调用其所在的那个方法的对象本身。
Example # 2$this伪变量的示例:
<?php
class A
{
function foo()
{
if(isset($this))
{
echo '$this is defined (';
echo get_class($this);
// get_class()函数返回对象的类名
echo ")\n";
}
else
{
echo "\$this is not defined.\n";
}
}
}
$a = new A();
$a->foo();
?>
以上列子输出结果为:
$this is defined (A)new
要创建一个类的实例,必须使用关键字new。
如果在new之后跟着的是一个包含有类名的字符串string,则该类的实例的一个实例被创建。如果该类属于命名空间,则必须使用其完整名称。
Example # 3创建实例
<?php
// new关键字后面直接跟类名
$instance = new A();
// 也可以这样做
$className = 'A';
$instance = new $className(); // A()
// 这两种方法都可以创建一个instance实例。
// 输出:$this is defined (A)
?>Example # 4对象赋值
<?php
class SimpleClass{
// 声明属性
public $var = 'a default value';
// 声明属性
public function desplayVar()
{
echo $this->var;
}
}
$instance = new SimpleClass();
$assigned = $instance;
$refernce = &$instance;
$instance->var = '$assigned will have this value';
$instance = null; // $instance and $reference become null
var_dump($instance);
var_dump($refernce);
var_dump($assigned);
?>
输出内容如下:
NULL
NULL
object(SimpleClass)#1 (1) {
["var"]=>
string(30) "$assigned will have this value"
}PHP符号: “ ::”
php中的::是调用类中的静态方法或者常量,属性的符号。使用“::”无需创建实例,可直接使用类名。
属性
类的变量成员叫做“属性”,或者“字段”、“特征”,在本文档统一称为“属性”。属性声明是由关键字public,protected或者private开头,然后跟着一个普通的变量声明来组成。属性中的变量可以初始化,但是初始化的值必须是常数。
提示:如果直接使用var声明属性,而没有用public,protected或者private之一,PHP5会将其视为public。
在内的成员方法里面,可以使用->(对象运行符):$this->property(其中property)是该属性名这种方式来访问非静态属性。静态属性则使用“::”(双冒号):self:$property来访问。稍后会详细介绍static关键字。
Example # 5
<?php
class myClass{
const constant = 'constant value';
function showConstant(){
echo $this::constant."\n";
}
}
// 这里直接使用::符号来访问类中常量,无需创建实例
echo myClass::constant;
// 这里通过实例化的方式来访问类中的常量
$c = new myClass();
$c->showConstant();
?>类常量
可以把在类中始终保持不变的值定义为常量。在定义和使用常量的时候不需要使用$符号。
常量的值必须是一个定值,不能是变量,类属性,数学运算或函数调用。
Example # 6
<?php
class myClass{
const constant = 'constant value';
function showConstant(){
echo $this::constant."\n";
}
}
// 这里直接使用::符号来访问类中常量,无需创建实例
echo myClass::constant;
// 这里通过实例化的方式来访问类中的常量
$c = new myClass();
$c->showConstant();
?>
类的自动加载
在编写面向对象(OOP)程序时,很多开发者为每个类新建一个PHP文件。这会带来一个烦恼:每个脚本的开头,都需要包含(include)一个常常的列表(每个类都有个文件)。
在PHP5中,已经抱在需要这样了。spl_autoload_register()函数可以注册人员数量的自动加载器,当使用尚未被定义的类(class)和接口(interface)时自动去加载。
范围解析操作符 (::)
范围解析操作符(也可称作 Paamayim Nekudotayim)或者更简单地说是一对冒号,可以用于访问静态成员,类常量,还可以用于覆盖类中的属性和方法。
当在类定义之外引用到这些项目时,要使用类名。
在PHP5.3.0起,可以通过变量来引用类,该变量的值不能是关键字(如:self,static,parent等)。
Example # 7在内的外部使用::符号
<?php
class myClass{
const CONST_VALUE = 'A constant value';
}
$c = new myClass();
// 自php5.3起,可以通过对象来访问
echo $c::CONST_VALUE;
echo myClass::CONST_VALUE;
Static(静态)关键字
声明类属性或方法为静态,就可以不实例化类而直接访问。静态属性不能通过一个类已实例化的对象来访问(但静态方法可以)。
如果没有指定访问控制,属性和方法默认为公有。
由于静态方法不需要通过对象即可调用,所以伪变量 $this 在静态方法中不可用。
静态属性不可以由对象通过 -> 操作符来访问。
用静态方式调用一个非静态方法会导致一个 E_STRICT 级别的错误。
就像其它所有的 PHP 静态变量一样,静态属性只能被初始化为文字或常量,不能使用表达式。所以可以把静态属性初始化为整数或数组,但不能初始化为另一个变量或函数返回值,也不能指向一个对象。
边栏推荐
- 【kotlin】第一天
- What is the MySQL database zipper table
- Rdkit | topological polarity surface area (TPSA)
- RPA (shadow knife) does not need to write code to capture the product information of an East
- Is the index of nine interview sites of ten companies invalid?
- 32 single chip microcomputer - PWM wave output
- 2021-06-16 STM32F103 EXTI 中断识别 使用固件库
- [Blue Bridge Cup monolithic unit] serial port communication
- 虚拟机浏览器花屏空白问题
- PostgreSQL database firstborn - background first-class citizen process startupdatabase startupxlog function enters recovery mode
猜你喜欢

Cluster hui dsm7 add suite source

One year experience interview byte Tiktok e-commerce, share the following experience!

Is the index of nine interview sites of ten companies invalid?

Yyds dry goods inventory rapid establishment of CEPH cluster

Arduino about software uninstallation and library uninstallation

2022年的WordPress网站安全问题

Le Code est correct, mais les données de la base de données ne sont pas affichées.
![[kotlin] first day](/img/51/18b394a6bf0ab74b71e5c59ad3341c.png)
[kotlin] first day
![[actual combat] ACM players illustrate leetcode using stack to realize queue](/img/f7/0a21f2fdc7c18f352c1b134d27c21c.jpg)
[actual combat] ACM players illustrate leetcode using stack to realize queue

JVM memory model concepts
随机推荐
Flutter returns to the black screen of the previous page
/home/ljx/miniconda3/compiler_ compat/ld: cannot find crtbeginS. o: There is no such file or directory
Send using queue mailbox
Figure neural network and cognitive reasoning - Tang Jie - Tsinghua University
面试鸭 面试刷题 网站系统源码
25 parameter estimation - Determination of sample size
Complex four operations (23 lines of concise code)
1004 Counting Leaves (30 分)
[untitled]
Cobaltstrike office macro virus utilization
结构体类型的三种声明方式
JVM内存模型概念
Vision_ Transformer code exercise
Permission management
Haidilao is expected to have an annual net loss of 3.8 billion to 4.5 billion and close more than 300 stores
[kotlin] first day
Yyds dry goods inventory junit5 learning 3: assertions class
Qunhui dsm7 add kit source
[kotlin] premier jour
How MySQL closes a transaction