这些对象调用之间有什么区别?
非静态:
$var = new Object;
$var->function();
Run Code Online (Sandbox Code Playgroud)
静态的:
$var = User::function();
Run Code Online (Sandbox Code Playgroud)
而且class为什么我应该为函数使用static属性?
例:
static public function doSomething(){
...code...
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*iot 41
根据定义,静态函数不能也不依赖于类的任何实例属性.也就是说,它们不需要执行类的实例(因此可以在没有首先创建实例的情况下执行,因此可以执行).从某种意义上说,这意味着该函数不会(并且永远不需要)依赖于类的成员或方法(公共或私有).
Cor*_*ius 10
差异在于变量范围.想象一下你有:
class Student{
public $age;
static $generation = 2006;
public function readPublic(){
return $this->age;
}
public static function readStatic(){
return $this->age; // case 1
return $student1->age; // case 2
return self::$generation; // case 3
}
}
$student1 = new Student();
Student::readStatic();
Run Code Online (Sandbox Code Playgroud)
你的静态函数无法知道$ this是什么,因为它是静态的.如果可能有$ this,它将属于$ student1而不是Student.
它也不知道什么是$ student1.
它适用于案例3,因为它是属于类的静态变量,与之前的2不同,它属于必须实例化的对象.
| 归档时间: |
|
| 查看次数: |
20676 次 |
| 最近记录: |