11

I want to have a string variable for a PHP class, which would be available to all methods.

However, this variable is quite long, so I want to separate it into multiple lines.

For example,

$variable = "line 1" .
            "line 2" .
            "line 3";

But above doesn't work.

I tried EOD, but EOD is not allowed within class. And when I declare it outside the class, I can't access the variable from within the class.

What is the best way?

Anthony Forloney
  • 90,123
  • 14
  • 117
  • 115
ericbae
  • 9,604
  • 25
  • 75
  • 108
  • 1
    I don't see any reason why the above won't work. Can you post exactly your code. Thanks. – Ivo Sabev Apr 09 '10 at 04:45
  • You can surely span variable's across multiple lines, can you post the code and exactly how it doesn't work? – Anthony Forloney Apr 09 '10 at 04:47
  • You can access variables outside the class using the `global` keyword or the `$GLOBALS` superglobal array, by the way. I don't recommend this, of course. – Zarel Apr 09 '10 at 04:54
  • Chalk up one more thing PHP can't do that every other language on earth can without hastle. – ThorSummoner Jul 01 '14 at 20:06

3 Answers3

11

If you are using PHP >= 5.3, you could use HEREDOC syntax to declare your string :

class MyClass {
    public $str = <<<STR
this is
a long
string
STR;

}

$a = new MyClass();
var_dump($a->str);

But this :

  • is only possible with PHP >= 5.3
  • and the string must not contain any variable
    • this is because the string's value must be known at compile-time
    • which, btw, explains why the concatenation, with the ., will not work : it's done at execution time.

And another drawback is that this will put newlines in the string -- which might, or not, be a bad thing.


If you are using PHP <= 5.2 :

You can't do that ; a solution could be to initialize the string in your class' constructor :

class MyClass {
    public $str;
    public function __construct() {
        $this->str = <<<STR
this is
a long
string
STR;
    }
}

(same not with newlines)

Or, here, you can do strings concatenations :

class MyClass {
    public $str;
    public function __construct() {
        $this->str = 'this is' .
                     'a long' .
                     'string';
    }
}

(this way, no newlines)


Else, you can have a string that's surrounded by either single or double quotes, and put it on several lines :

class MyClass {
    public $str = "this is
a long
string";
}

(Here, again, you'll have newlines in the resulting string)

Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
  • 1
    _this is because the string's value must be known at compile-time_ - wrong. – user187291 Apr 09 '10 at 04:56
  • @stereofrog http://fr2.php.net/manual/en/language.oop5.properties.php says *This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time* -- so it this really wrong ? – Pascal MARTIN Apr 09 '10 at 05:00
  • Oh ; do you have any working example of initializing a class property with a non-constant value ? – Pascal MARTIN Apr 09 '10 at 05:23
  • i've posted that once, basically it goes like this: `define('foo',rand()); class x { var $bar=foo; };` – user187291 Apr 09 '10 at 05:33
  • Oh I see ; didn't think about using defines in this situation ^^ thanks for the note :-) – Pascal MARTIN Apr 09 '10 at 06:29
  • None of these methods work for a static class ... -_- newlines in some cases of a static string literal are not acceptable. – ThorSummoner Jul 01 '14 at 20:05
2
$var = "this is a really long variable and I'd rather have it " .
 "span over multiple lines for readability sake. God it's so hot in here " .
 "can someone turn on the A/C?";
echo $var;

Which outputs:

this is a really long variable and I'd rather have it span over multiple lines for readability sake. God it's so hot in here can someone turn on the A/C?

What you have now works using the string concatenation operator. If you can post more information regarding your issue, some code or perhaps a further explanation of how it doesn't work. More information will lead you to a better answer.

Anthony Forloney
  • 90,123
  • 14
  • 117
  • 115
  • 1
    This will work for a variable inside a method ; but will it work for a class property ? *(which I believe is what's the question's about)* – Pascal MARTIN Apr 09 '10 at 05:23
  • Hello, as Martin said, I wanted to declare the variable OUTSIDE of the class and then access it within a method. $var = "line1". "line2"; works if I declare it inside a function, but doesn't if I do it outside. It won't even let me. – ericbae Apr 09 '10 at 06:47
  • Ah, that I have not tried, I could test it out when I am back from work, if need be. But it seems you had already found a solution. – Anthony Forloney Apr 09 '10 at 11:38
0

I'm using PHP 5.5.9 and have come across a similar issue only with class constants. I want to use a somewhat long string as a constant but I don't want:

  • really long lines of code
  • newlines showing up in the text at the break points
  • the property to be mutable
  • the property to be inaccessible outside the class

I think the solution here is something that is done a lot in the Laravel 5 scaffolding and why they kept doing this had me baffled until now. What they do is something like:

public static function getLongPropertyString()
{
    return 'A a string that can be arbitrarily long and contain as ' .
        'many breaks in the code as you want without line breaks ' .
        'appearing in the resulting string.';
}

This method provides an immutable string. You don't strictly get that by creating a protected/private variable with getters since its still mutable internally. Only changing the code or overriding can change this string. Another pro is that making it static allows a single "instance" per class.

Unfortunately, now your code would be Class::getProperty() rather than just Class::property. Another downside is that the concatenation would be done every time you call the function but depending on how you use this, that cost is typically negligible.

It would be cool if the PHP compiler were able to recognize that the concatenation operation on only values already known at compile time can be run at compile time and the result substituted (beings more knowledgeable than myself know why this is so).

jeteon
  • 3,471
  • 27
  • 40
  • If you don't add a setter and no methods change it, a private variable is also immutable unless you change the code. But returning the string from a method _might_ give a more clear intent as to what you're doing. – Michał Tatarynowicz Sep 24 '15 at 18:33
  • I agree. I just suggested this form since there is no implicit way to change the string without intentionally overriding the method or changing the text inside i.e. the only way to change the string is to override the method or change the code inside it. In this regard its _closer_ to being immutable since we've removed unintentional means of modifying it. – jeteon Sep 25 '15 at 07:54