static

<?php
class SomeClass
{
    protected $some_member;//受保护
    protected static $test = 'test';
    static $static_test = 'static';
    public $public_str = 'public';
    public function __construct()
    {
        $this->some_member = 1;
    }

    public static function getSomethingStatic()
    {//静态方法
        // return $this->some_member * 5; //错误的使用方法
        $test = new SomeClass();//静态方法  所以要实例化这个类;而不能直接用 $this->
        return $test->some_member * 5;
    }

    public function get_test(){
        return self::$test;
    }
}

class ChildClass extends SomeClass{
    public function childprotected(){
        return parent::$test;
    }
}

echo SomeClass::$static_test. "\n";
// echo SomeClass::$test. "\n";// Uncaught Error: Cannot access protected property SomeClass::$test
echo SomeClass::getSomethingStatic(). "\n";//静态方法不需要通过类实例化的对象即可调用

$some = new SomeClass();
echo  $some->getSomethingStatic(). "\n";//静态方法也可通过类实例化的方法来调用
echo $some->get_test(). "\n";
echo $some::$static_test. "\n";

//将类名赋值给变量
$class_name = 'SomeClass';
echo $class_name::$static_test. "\n";

// echo $some->static_test;//Undefined property: SomeClass::$static_test 静态属性不能通过一个类已实例化的对象来访问
//echo $some->$test;//报错:Undefined variable: test
//echo SomeClass::$test;//报错: Fatal error: Uncaught Error: Cannot access protected property SomeClass::$test
//echo SomeClass::$public_str;// Uncaught Error: Access to undeclared static property: SomeClass::$public_str ; 用静态方式调用一个非静态方法会导致一个E_STRICT级别的错误

// echo ChildClass::$test. "\n"; //Uncaught Error: Cannot access protected property ChildClass::$test
echo ChildClass::childprotected(). "\n";//输出父类受保护的变量
echo ChildClass::$static_test. "\n";//输出父类共有变量

 

/**************不喜勿喷,谢谢!***************/

 

posted on 2019-04-19 14:40  Megan99  阅读(162)  评论(0编辑  收藏  举报