YI YANG YI YANG - 1 year ago 44
PHP Question

Do I need to declare a variable before initialise it in PHP constructor

I have a question about variable declare in PHP, I know this question may be little bit stupid. I have the following code

Class Test{
function __construct(){
$this->test = 'helloworkd';
function test(){
echo test;
$test = new Test();

It seems like I can use the test variable without declaring it. My question is why the test() method can access the test variable? Is the test a global variable?

Thanks for your help!

Answer Source

My question is why the test() method can access the test variable?

PHP unlike some other languages allows you to assign values to variables without first declaring them. The interpreter will initialize them for you. This is poor practice because it makes code harder to read and debug, and because it can cause errors if you try to read a variable that was never declared:

$nonexistentArray['key'] = 7; //Bad practice, but PHP won't complain
$a = $fakeArray['key']; //Undefined variable error

Even in the second case, PHP will continue to execute the rest of the script, but it will complain.

Is the test a global variable?

No. It lives in the local scope.

function myFunc(){
    //$arr was never declared, neither was $arr['key'], but PHP won't complain

//Undefined var error. The $arr that was initialized in myFunc is not global

A good IDE will complain if you try to use a variable that you never declared. In your case, when in the constructor you do:

$this->test = 'helloworkd';

PHP will initialize this class property for you. Now the rest of your code can use it, including the test() method. If it seems like a global var, it's not. It's a class property. If you tried to access it as just test from outside the class, you would not be able to. You'd have to use the accessor operator -> in $test->test or $this->test.