Home > Backend Development > PHP Tutorial > PHP静态方法和非静态方法的使用场景

PHP静态方法和非静态方法的使用场景

WBOY
Release: 2016-06-20 12:34:20
Original
1544 people have browsed it

思考案例

静态成员

类中的成员加入static修饰符,即是静态成员.可以直接使用类名+静态成员名访问此静态成员,因为静态成员存在于内存,非静态成员需要实例化才会分配内存,所以静态方法不能访问非静态的成员.因为静态成员存在于内存,所以非静态方法可以直接访问类中静态的成员.

非成静态员

所有没有加Static的成员都是非静态成员,当类被实例化之后,可以通过实例化的类名进行访问..非静态成员的生存期决定于该对象的生存期..而静态成员则不存在生存期的概念,因为静态成员始终驻留在内容中.

class user {    private static $count = 0;    public function __construct() {        self::$count = self::$count + 1;    }    public function getCount() {        return self::$count;    }    public function __destruct() {        self::$count = self::$count - 1;    }}$user1 = new user();$user2 = new user();$user3 = new user();echo $user1->getCount();echo "";unset($user3);echo $user1->getCount();
Copy after login
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template