Php $this->;之间的区别是什么;id和$id
$this->id和$id之间的区别是什么Php $this->;之间的区别是什么;id和$id,php,this,Php,This,$this->id和$id之间的区别是什么 class Test{ public $id; function Test(){ $this->id = 1; } } === 如何从其他类获取变量 class TestA{ public $test; function TestA(){ $this->test = new Test(); echo $this->test->id; } } 在您的示例中没有区别,但是当您的方法中有同名的内部变量时
class Test{
public $id;
function Test(){
$this->id = 1;
}
}
===
如何从其他类获取变量
class TestA{
public $test;
function TestA(){
$this->test = new Test();
echo $this->test->id;
}
}
在您的示例中没有区别,但是当您的方法中有同名的内部变量时,使用
$this->variable\u name
会很有用:
class test{
public $id;
function test($id){
$id = 1; // method parameter
$this->id = 2; // object member
}
php
无法以C++
、Java
和C#
的方式工作
在php中,您应该始终使用$this
引用和->
操作符访问实例变量
因此,第一个代码将
1
分配给实例id
属性,第二个代码将1
分配给本地$id
变量。在示例中,实际上没有什么区别。您也可以通过使用$this
对其进行限定来访问成员变量,因为所有成员变量都属于$this
。正如MarinJuraszek所说,考虑范围是很重要的。<代码> $ $-> ID 指的是它可以在类方法中访问的类属性,也可以通过它的Obj.
来访问。$id
只是一个可以在创建它的本地作用域中访问的变量。另外,请参阅文档:请注意,您缺少一对}
$this->id
不是类成员,而是实例成员。如果它是静态的,并且作为self::$id:
class test{
public $id;
function test($id){
$id = 1; // method parameter
$this->id = 2; // object member
}