PHP 面向对象详解

PHP 面向对象 (五)静态方法

2020-01-12  本文已影响0人  一句话儿
作用: 操作静态变量

定义: 修饰符  static function name()

调用方式
    类外部调用方法
        类名::function
        对象名->function
    类内部调用方法
        self::function 推荐使用
        类名::function
        $this->function
        static::function

注意: 静态方法 只能访问 静态属性, 而不能访问  非静态属性

使用:静态方法不许要实例化对象即可调用,最佳实践:单例模式
demo6.php
<?php

/**
 * Desc: 静态变量
 * User: zyy
 * Date: 2019-12-08
 * Time: 下午 23:43
 */
class Student{
    public $class = '3年2班';
    public static $country;

    function __construct($country)
    {
        self::$country = $country;
    }

    public function getCountry()
    {
        echo self::$country;echo "<br/>";
    }

    public static function getStatic()
    {
        echo self::$country;echo "<br/>";
//        echo $this->class;//报错,用类名调用静态方法时,$this类对象还不存在
    }

}



$stu1 = new Student('中国');

echo Student::$country;echo "<br/>";

$stu1->getCountry();

Student::getStatic();echo "<br/>";


上一篇下一篇

猜你喜欢

热点阅读