PHP object properties

I am new to OOP in PHP, and I find the difference between the following two expressions that are hard to understand.

    $object->$foo;
    $object->foo;

Perhaps this is my fault, but I could not find the corresponding part in the manual.

+3
source share
2 answers

The first call $obj->$foouses a so-called variable. Check this:

class A { 
    public $foo = 1;
}

$a = new A();
$foo = 'foo';

// now you can use both
echo $a->$foo;
echo $a->foo;

Follow the manual on variables

+2
source

Well, to fully understand the somewhat weird look $object->$foo, you need to understand two things about PHP:

Variable names

Most time variables in PHP are pretty straight forward. They start with a character $, have one character [a-zA-Z_], and then any number of characters [a-z-A-Z0-9_]. Examples include:

$var  = 'Abcdef';
$_GET = [];
$a1   = 123;
// And so on...

PHP , , , , , - ({}), :

${null}  = 'It works'; echo ${null};
${false} = 'It works'; echo ${false};
${'!'}   = 'It works'; echo ${'!'};

// Slightly weirder...
${(int)trim(' 5 ')}       = 'It works'; echo ${5};
${implode(['a','b','c'])} = 'It works'; echo $abc;

: , , , . PHP, .

: - , .

- , PHP. :

${"abc"} = 'Abc...';
echo $abc;

"abc", , $abc.

( ), , ... :

$abc = 'Abc...';
$varName = 'abc';
echo ${$varName}; // echo $abc

. "" :

$abc = 'Abc...';
$varName = 'abc';
echo $$varName; // echo $abc

$object->$foo " ",

$object = new stdClass;
$object->abc = 'The alphabet!';

$foo = 'abc';
echo $object->$foo;
echo $object->{$foo};  // The same
echo $object->{'abc'}; // The same

, . .

+2

All Articles