Home php教程 php手册 php5中类的学习

php5中类的学习

Jun 13, 2016 pm 12:29 PM
php php5 code copy study constant of

复制代码 代码如下:


class TEST     
{     
    const NAME = 'value'; // 常量     
    public $name = 'value'; // 属性     
    public function name() // 方法     
    {     
        echo 'value';     
    }     
}     
?>    



在这之中,属性和方法又可以使用public, protected, private三个不同的关键字来将属性和方法的作用范围做进一步的区分,带有private关键字的属性和方法,只有所在的类中的方法才能调用;带有protected关键字的属性和方法,除了自己以外,自己的父类和子类中的方法也可以调用;带有public关键字的属性和方法,则可以从实例化以后的对象中进行调用,这样做最大的好处给所有的属性和方法增加了一些描述的特征,更便于整理和组织代码的结构。const关键字先跳过,和后面的static一起讲。

static关键字是有别于public, protected, private的另一类型关键字(因此可以和public, protected, private叠加起来使用):

复制代码 代码如下:


class TEST     
{     
    public static function name()      
    {     
        echo 'value';     
    }     
}     
?>


带有static关键字的方法,可以在不对类进行实例化的情况下直接通过“::”符号调用,和public, protected, private的搭配,也可以让调用区分权限,但是一般都是和public搭档,前面提到的常量关键字const,应该就是public static类型的,因此只能通过self::NAME,TEST::NAME这样的形式调用常量,后面的__construct,__destruct等方法,都是属于static。

类的结构部分,最后介绍的两个关键字是abstract和final,abstract关键字表示这个类必须被他的子类覆写,而final关键字表示这个类必须不能被他的子类覆写,这两个关键字的功能是正好相反的,带有abstract的方法被成为抽象方法,带有抽象方法的类,成为抽象类,这个在后面还有介绍。

类的使用:

类的使用主要有两种方法,一种是使用new关键字,另一种是使用“::”符号:

PHP代码 

复制代码 代码如下:


class TEST     
{     
    public static function name()      
    {     
        echo 'value';     
    }     
}     
//方法1:使用new关键字     
$test = new TEST;     
$test->name();     

//方法2:使用“::”符号     
TEST::name();     
?> 

  

(1):使用new关键字成为实例化,上面的$test就是一个通过TEST类实例化而产生的对象,$test->name()称为调用$test对象的name方法。
(2):使用new关键字使用类的时候,可以使用$this来指代类本身。
(3):使用“::”符号的前提是方法必须是带有static关键字的,使用new关键字时,被调用的方法,必须带有public关键字(一个方法如果不带public, protected, private中的任何一个关键字,则默认为public)
(4):同一个类可以通过new关键字被实例成多个不同的对象,但是彼此之间的是隔离的;“::”符号在使用的时候,方法在多次使用之间,是共享的:

PHP代码

复制代码 代码如下:


class TEST1     
{     
    public $name = 0;     
    public function name()      
    {     
        $this->name = $this->name + 1;     
    }     
}     

$test1 = new TEST1;     
$test2 = new TEST1;     
$test1->name(); //$name1 == 1     
$test2->name(); //$name1 == 1     

/*--------------------------------------------*/    

class TEST2     
{     
    public static $name = 0;     
    public static function name()      
    {     
        TEST2::$name = TEST2::$name + 1;     

    }     
}     
TEST2::name(); // $name == 1     
TEST2::name(); // $name == 2     
?>    

类的关系:

类与类之间的关系,主要有抽象,接口和继承:

PHP代码 

复制代码 代码如下:


abstract class TEST1 // 抽象     
{     
    abstract public function name1();     
    public function name2()     
    {     

    }     
}     

class TEST2 extends TEST1 implements TEST3 // 继承     
{     
    public function name1()     
    {     

    }     
}     

interface TEST3 // 接口     
{     
    public function name2();     
}     
?>   



(1)带有abstract关键字的类是抽象类,带有abstract关键字的方法是抽象方法,抽象类中的抽象方法,必须在子类中被覆写。
(2)带有interface关键字的类,就是接口,接口不允许实现任何的方法,接口中所有的方法,都必须在子类中被覆写。
(3)带有 classA extends classB 或者 classA implements classB 字样的就是继承,extends表示继承另一个类,implements表示继承另一个接口,一次只能extends一个类,但是可以implements多个接口。
(4)抽象类,接口,以及最终继承并实现的方法,都必须是public的。

在继承的过程中,子类会覆写父类的同名方法,这个时候如果需要在子类中调用父类的方法,可以使用parent关键字或者类名加上“::”符号调用:

PHP代码 

复制代码 代码如下:


class TEST1 extends TEST2     
{     
    public function name()     
    {     
        echo parent::name2();     
        echo TEST2::name2();     
    }     
}     
class TEST2     
{     
    public function name2()     
    {     
        echo 'value2';     
    }     
}     
$test = new TEST1;     
$test->name();     
?>  

 

这里再解释一下“::”方法在类中的作用,一个作用是在没有实例化的情况下调用常量(其实也理解成static就可以了),static属性和方法,再一个是在类的内部,通过self,parent和类名建立便捷的调用通道。

对象于对象之间的关系,主要是“==”等于,“===”全等于,不等于和clone:

PHP代码
class TEST    
{    
    public function name()    
    {    

    }    
}    

$test1 = new TEST;    
$test2 = new TEST;    
$test3 = $test1;    
echo $test1 == $test2 ? true : false; // true    
echo $test1 == $test3 ? true : false; // true    
echo $test2 == $test3 ? true : false; // true    
echo $test1 === $test2 ? true : false; // false    
echo $test1 === $test3 ? true : false; // true    
echo $test2 === $test3 ? true : false; // false    
?>   

(1)两个类只要拥有相同的属性和方法,就是“==”等于。
(2)两个类必须是指向的同一个对象,才能是“===”全等于。

clone比较特殊,在上面的例子中,$test3 = $test1的过程并不是给了 $test3 一份 $test1 对象的拷贝,而是让 $test3 指向了 $test1,如果一定要获得一份$test1的拷贝,就必须使用clone关键字:

PHP代码

复制代码 代码如下:


$test3 = clone $test1;     
?>    



类的钩子:

__autoload:
是一个函数名,也是唯一一个在类的外部使用的钩子,在实例化一个对象的时候,如果没有预先载入类,就会调用这个钩子。

__construct
在类被实例话的时候,被调用的钩子,可以做一些初始化的操作。

__destruct
在类被销毁的时候,被调用的钩子。

__call
当对象试图调用一个不存在的方法的时候,被调用的钩子

__sleep
当使用serialize()函数对一个类进行序列话操作的时候,会调用这个钩子

__wakeup
当使用unserialize()函数对一个类进行反序列话操作的时候,会调用这个钩子

__toString
当一个对象将被转变为字符串的时候,会调用这个钩子(比如echo的时候)

__set_state
当调用var_export()函数操作一个类的时候,会调用这个钩子

__clone
当使用clone关键字对一个类进行拷贝操作的时候,会调用这个钩子

__get
在获取一个类中的属性值的时候,会调用这个钩子

__set
在设置一个类中的属性值的时候,会调用这个钩子

__isset
在使用isset()函数对类中的属性值进行判定的时候,会调用这个钩子

__unset
在使用unset()函数销毁一个属性值的时候,会调用这个钩子

类的小技巧:

在实例话一个类的时候,可以使用这样的形式给__construct钩子传递参数:

PHP代码 

复制代码 代码如下:


class TEST     
{     
    public function __construct($para)     
    {     
        echo $para;     
    }     
}     

$test = new TEST('value'); // 显示 value     
?>   



foreach()函数可以用来对类或者对象中的属性进行遍历,遍历的时候会先判断public, protected, private的情况而显示:

PHP代码

复制代码 代码如下:


class TEST     
{     
    public $property1 = 'value1';     
    public $property2 = 'value2';     
    public $property3 = 'value3';     

    public function name()     
    {     
        foreach($this as $key => $value)     
        {     
            print "$key => $value\n";     
        }     
    }     
}     

$test = new TEST;     
foreach($test as $key => $value)     
{     
    print "$key => $value\n";     
}     
$test->name();     
?>    


在给类中的方法传递参数的时候,可以对参数进行强制的判定,这里只支持对数组和对象的判定:

PHP代码

复制代码 代码如下:


class TEST1     
{     
    public function name( TEST2 $para )     
    {     

    }     
}     

class TEST2     
{     

}     

$test2 = new TEST2;     
$test1 = new TEST1;     

$test1->name('value'); // 会报错,因为这个参数必须是TEST2实例化以后的对象     
$test1->name($test1); // 不会报错     
?>    



兼容php4的语法:

php5的类是往下兼容php4的,这些php4时代的语法也得到了继承,但是并不建议在php5的环境中使用。

(1)使用var预设属性,会自动转换成public。

(2)使用类名作为构造函数,在没有__construct构造方法的情况下,会寻找和类名相同的函数作为构造函数。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles