Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple PHP class, undefined variable?

Tags:

php

I'm learning about classes and objects in PHP, and I'm getting really confused. This is what I have so far:

<?php

class ipInfo {
    public $test1 = 'test';
}

$test = new ipInfo();
echo $test->$test1;

?>

Whenever I run it, I get these errors:

Notice: Undefined variable: test1 in //// on line 9

Fatal error: Cannot access empty property in //// on line 9
like image 726
Carpetfizz Avatar asked Oct 18 '13 01:10

Carpetfizz


People also ask

How do I fix undefined variable error in PHP?

It can be solved either by declaring a variable global and then using isset() to see if it is set or not.

Why is my variable undefined PHP?

Undefined variable: the variable's definition is not found in the project files, configured include paths, or among the PHP predefined variables. Variable might have not been defined: there are one or more paths to reach the line with the variable usage without defining it.

How do you handle undefined variables?

undefined variables can be corrected by DEFINING them. for instance: $place = ''; OR $place = null; defines the variable.

How can write undefined in PHP?

php class undef1{function __toString(){return 'undefined';}} function undef1(){ static $C; if($C===null){$C = new undef1();} return $C; } echo 'undef1 in string context : '; var_dump( undef1(). ''); echo 'undef1 in boolean context: '; var_dump( !!


1 Answers

Object properties don't need the second $ (unless you are using variable varibles).

echo $test->test1;

You use the $ to reference the variable and then the -> to specify which propery you are looking at.

If you on the other hand have a variable with the value of test1 called $var you could do this:

$var='test1';
echo $test->$var;

Which would work as the code would interpret the VALUE inside the $var and assume you meant that property.

like image 139
Fluffeh Avatar answered Sep 24 '22 20:09

Fluffeh