java static静态方法源码讲解

时间:2019-04-19
本文章向大家介绍static,主要包括static使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
 1 <?php
 2 class SomeClass
 3 {
 4     protected $some_member;//受保护
 5     protected static $test = 'test';
 6     static $static_test = 'static';
 7     public function __construct()
 8     {
 9         $this->some_member = 1;
10     }
11 
12     public static function getSomethingStatic()
13     {//静态方法
14         // return $this->some_member * 5; //错误的使用方法
15         $test = new SomeClass();//静态方法  所以要实例化这个类;而不能直接用 $this->
16         return $test->some_member * 5;
17     }
18 
19     public function get_test(){
20         return self::$test;
21     }
22 }
23 
24 class ChildClass extends SomeClass{
25     public function childprotected(){
26         return parent::$test;
27     }
28 }
29 
30 echo SomeClass::$static_test. "\n";
31 // echo SomeClass::$test. "\n";// Uncaught Error: Cannot access protected property SomeClass::$test
32 echo SomeClass::getSomethingStatic(). "\n";//静态方法不需要通过类实例化的对象即可调用
33 
34 $some = new SomeClass();
35 echo  $some->getSomethingStatic(). "\n";//静态方法也可通过类实例化的方法来调用
36 echo $some->get_test(). "\n";
37 echo $some::$static_test. "\n";
38 
39 //将类名赋值给变量
40 $class_name = 'SomeClass';
41 echo $class_name::$static_test. "\n";
42 
43 // echo $some->static_test;//Undefined property: SomeClass::$static_test
44 //echo $some->$test;//报错:Undefined variable: test
45 //echo SomeClass::$test;//报错: Fatal error: Uncaught Error: Cannot access protected property SomeClass::$test
46 
47 // echo ChildClass::$test. "\n"; //Uncaught Error: Cannot access protected property ChildClass::$test
48 echo ChildClass::childprotected(). "\n";//输出父类受保护的变量
49 echo ChildClass::$static_test. "\n";//输出父类共有变量
50 
51  
52 
53 **************不喜勿喷,谢谢!***************

 

上一页 下一页

原文地址:http://www.manongjc.com/article/107175.html