我有一个关于PHP中的变量声明的问题,我知道这个问题可能有点愚蠢。我有以下代码
<?php
Class Test{
function __construct(){
$this->test = 'helloworkd';
}
function test(){
echo $this->test;
}
}
$test = new Test();
$test->test();
似乎我可以在不声明的情况下使用测试变量。我的问题是为什么 test() 方法可以访问测试变量?测试是全局变量吗?
感谢您的帮助!
我的问题是为什么 test() 方法可以访问测试变量?
与其他一些语言不同,PHP 允许您在不先声明变量的情况下为变量赋值。 解释器将为您初始化它们。 这种做法很糟糕,因为它会使代码更难阅读和调试,并且如果您尝试读取从未声明的变量,可能会导致错误:
<?php
$nonexistentArray['key'] = 7; //Bad practice, but PHP won't complain
$a = $fakeArray['key']; //Undefined variable error
即使在第二种情况下,PHP 也会继续执行脚本的其余部分,但它会抱怨。
测试是全局变量吗?
不。它存在于本地范围内。
<?php
function myFunc(){
//$arr was never declared, but PHP won't complain
$arr['key'][]=7;
}
myFunc();
//Undefined var error. The $arr that was initialized in myFunc is not global
print_r($arr);
一个好的 IDE 会抱怨,如果你尝试使用一个你从未声明过的变量。在您的情况下,在构造函数中执行以下操作时:
$this->test = 'helloworkd';
PHP 将为您初始化此类属性。现在,其余代码都可以使用它,包括 test()
方法。如果它看起来像一个全局变量,那么它不是。这是一个类属性。 如果您尝试仅从类外test
访问它,您将无法访问。您必须在 $test->test
或 $this->test
中使用访问器运算符->
。
许多"测试"!你在构造器中有 asign test="helloworld",所以它为每一个新的 Test() 创建一个值。
$x = new Test();
$y = new Test();
echo $x->test(); //"helloworld"
echo $y->test(); //"helloworld"
我会声明你的变量。这使得看到您的代码的任何其他人都更容易阅读代码。
例如:
<?php
Class Test {
public $test;
function __construct($test){
$this->test = $test;
}
function test(){
echo $this->test;
}
所以现在我们有一个公共变量,可以通过调用此类的实例访问它$instance>测试;
如果您不希望这样做,则可以将公共更改为私有或受保护您可以在此处阅读有关此内容的信息:http://php.net/manual/en/language.variables.scope.php
创建此类实例时作为参数传递的任何内容都将分配给$test变量。
我的问题是为什么 test() 方法可以访问测试变量?
不能。它正在尝试访问常量test
,如果要访问类变量,请使用$this->test
。
例如:
<?php
echo foo;
会回显出一个字符串"foo",并吐出一个通知:使用未定义的常量 foo - 假设"foo"在...
<?php
class test{
public $test;
public function __construct(){
$this->test = 'helloworkd';
}
$newtest = new Test();
echo $newtest->test;
?>