Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing object's method within string

Recently I was reading php documentation and found interesting note in string section:

Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

See www.php.net/manual/en/language.types.string.php

It says, that I can't use curly syntax to get value returned by object's method call. Is it a mistake in manual or I misunderstood it, because I tried the following code and it works just fine:

<?php
class HelloWorld
{
    public static function hello() 
    {
        echo 'hello';
    }
}
$a = new HelloWorld();

echo "{$a->hello()} world";
like image 604
Wild One Avatar asked Oct 23 '22 05:10

Wild One


1 Answers

PHP DOC Says

will not work for accessing the return values of functions or methods or the values of class constants or static class variables

$a->hello() is not how to call a static method in PHP and also not a constants or static class variables This is what they mean :

class HelloWorld {
    const A = "A";//                <---- You can not use it for this 
    public static $B = "B";         <---- or this  

    public static function hello() {
        echo 'hello';
    }
}


$a = new HelloWorld();
$A = "{HelloWorld::A} world";       <-------- Not Work
$B = "{HelloWorld::$B} world";      <-------- Not Work
$C = "{HelloWorld::hello()} world"; <-------- Not Work

If you now try

$A = "X";    // If you don't define this it would not work
$B = "Y" ;   //<------------- -^

echo "{${HelloWorld::A}} world";  
echo "{${HelloWorld::$B}} world"; 

Output

X world           <--- returns X world instead of A
Y world           <--- returns Y world instead of B
like image 79
Baba Avatar answered Oct 29 '22 16:10

Baba