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
It can be solved either by declaring a variable global and then using isset() to see if it is set or not.
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.
undefined variables can be corrected by DEFINING them. for instance: $place = ''; OR $place = null; defines the variable.
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( !!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With