Can anyone tell me what is the differnce between:
class Test {
public $var; // I know this can be accessed from outside...
public function __construct($var) {
$this->var = $var; // This
$this->new_var = $var; // And this ... ? this is only internal like I would write private $new_var; ?
}
public function echoVar() {
echo $this->new_var;
}
}
答案 0 :(得分:2)
这两者之间实际上没有任何根本区别 - 如果您在PHP中写入未声明的属性(来自类内部或外部),它将动态创建新的公共属性。所以给出以下脚本:
<?php
class Test {
public function __construct() {
$this->foo = 'foo';
}
}
$test = new Test;
echo $test->foo;
您将获得输出foo
。请参阅https://eval.in/632326。
简而言之,如果要隐藏属性,则需要将属性明确声明为private
或protected
。
您还可以在类上实现魔术方法__get
和__set
,以便更好地处理读取或写入动态属性的调用。有关详细信息,请参阅overloading上的手册页。
答案 1 :(得分:0)
我会添加注释行来指定每个变量。
class Test {
public $var; // I know this can be accessed from outside...
//Variable/property that can be accessed from outside the class like you mentioned.
public function __construct($var) {
$this->var = $var; // This
//$this calls a non static method or property from a class, in this case the property `public $var`
$this->new_var = $var; // And this ... ? this is only internal like I would write private $new_var; ?
//Creates a new public property in the Test class
}
public function echoVar() {
echo $this->new_var;
//echo the property new_var from Test class.
}
}
答案 2 :(得分:0)
评论中的说明
class Test {
public $var; // This is a member variable or attribute.
// Something that this class has access to
// and any of its sub-children
public function __construct($var) {
$this->var = $var; //If you mean $this then it is
// the current instance of this class see below
//If you mean $var it is a the parameter that
//is passed to the method. See below as well
$this->new_var = $var; // update: this adds a public member to the object
// essentially another $var just not easily known.
// Not sure a good use for this except confusion and chaos.
// If it were just $new_var then it is a
// scoped variable in this method
}
}
$this
和parameters
$testPony = new Test("pony"); //An instance of test with a parameter of pony
$testUnicorn = new Test("unicorn"); //An instance of test with a parameter of unicorn
echo $testPony->var . "<br>";
echo $testUnicorn->var . "<br>";
echo $testPony->new_var . "<br>";
echo $testUnicorn->new_var . "<br>";
echo "<pre>";
var_dump($testPony);
上面会输出:
pony
unicorn
I like pony
I like unicorn
object(Test)#49 (3) {
["var"]=>string(4) "pony"
["new_var"]=>string(11) "I like pony"
}
作为一个注释,最终转储只显示公共成员,如果有私有的,它将采用格式(假设私有$ foo)["foo":"Test":private]=>NULL