PHP中static关键字以及与self关键字的区别

内容摘要
概述
正在学习设计模式,之前有一篇文章关于单例模式的文章,重新读了这篇文章,发现对static关键字掌握不是很牢靠,重新温习一下。
static关键字
PHP手册里对static关键字的介绍如
文章正文

概述

正在学习设计模式,之前有一篇文章关于单例模式的文章,重新读了这篇文章,发现对static关键字掌握不是很牢靠,重新温习一下。

static关键字

PHP手册里对static关键字的介绍如下:

例子

self vs static

用一个demo来直接说明self与static的区别。
self示例:

复制代码 代码如下:

<?php
class Vehicle {
    protected static $name = 'This is a Vehicle';
    public static function what_vehicle() {
        echo get_called_class()."\n";               
        echo self::$name;
    }
}
class Sedan extends Vehicle {
    protected static $name = 'This is a Sedan';
}
Sedan::what_vehicle();

程序输出:
复制代码 代码如下:

Sedan
This is a Vehicle

static示例:
复制代码 代码如下:

<?php
class Vehicle {
    protected static $name = 'This is a Vehicle';
    public static function what_vehicle() {
        echo get_called_class()."\n";       
        echo static::$name;
    }
}
class Sedan extends Vehicle {
    protected static $name = 'This is a Sedan';
}
Sedan::what_vehicle();

程序输出:

复制代码 代码如下:

Sedan
This is a Sedan

总结

看看上一篇文章,已经一个多月没更新过博客了,忙是一部分,主要的还是自己懈怠了,以后还得坚持。这篇文章写的也有点没感觉。


代码注释

作者:喵哥笔记

IDC笔记

学的不仅是技术,更是梦想!

© 2020 IDC笔记 . | 备案号:辽ICP备18000516号