Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to access a static variable inside a string with a heredoc syntax?

Lets say I have a static variable called $_staticVar in my class which I am trying to access like this. The variable has a member aString which has the string value of "my static variable"

    echo <<<eos

    <br/>This is the content of my static variable, 
    self::$_staticVar->$aString
    which is not getting accessed properly in heredoc syntax. <br/>

eos;

Output:

Notice: Undefined variable: _staticVar in /path/to/file.php on line some_line_number

<br/>This is the content of my static variable,
self::->my static variable,
which is not getting accessed properly in heredoc syntax.<br/>

The PHPdocs for heredoc doesn't say anything about this.


I have tried this:

    echo <<<eos

    <br/>This is the content of my static variable,<br/>
    {${self::$_staticVar->$aString}}<br/>
    which is not getting accessed properly in heredoc syntax. <br/>

eos;

and it does not work.
Output:

Notice: Undefined variable: _staticVar in /path/to/file.php on line some_line_number

<br/>This is the content of my static variable,
   
which is not getting accessed properly in heredoc syntax.<br/>


This is my PHP setting:

display_startup_errors = on
display_errors = On
error_reporting = E_ALL | E_STRICT

like image 526
ThinkingMonkey Avatar asked Oct 27 '25 10:10

ThinkingMonkey


1 Answers

I'm fairly certain you must use a local or imported variable for string interpolation. The easiest solution? Why, make it local of course:

    $_staticVar = self::$_staticVar; // or did you mean self::_staticVar? Not too clear on that.

    echo <<<eos

    <br/>Something {$_staticVar->something} more of something <br/>

eos;

As for the reasons your examples didn't work:

    echo <<<eos

    <br/>Something self::$_staticVar->{$something} more of something <br/>

eos;

Interpolates undefined variables $something and $_staticVar, which results in an empty string and a notice.

    echo <<<eos

    <br/>Something {${self::$$_staticVar->{$something}}} more of something <br/>

eos;

Interpolates the value of something that definitely doesn't exist and never will and it's all really confusing but you know it doesn't work.

like image 146
Ry- Avatar answered Oct 30 '25 01:10

Ry-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!