tags:

views:

206

answers:

4

Hello, what's the PHP equivalent of Ruby's "||=" assignment idiom?

The scenario is I want to instantiate an object or array "on demand," and not necessarily when a class is initialized.

I've tried to find this in the PHP docs, but I'm having difficulty finding things I need in there (miss the Ruby).

Thank you!

+2  A: 

I don't think PHP has a similar assignment syntax. You'll have to fake it with something like this:

if (empty($someVar))  $someVar = "DefaultVal";

Note: I'm not familiar with Ruby, so I read up on the ||= operator here. I'm not sure how that operator, as explained at that link, would help you do what you want either, but whatever.

Ryan Ballantyne
A: 

Similar question here

You might like to try out PECL Operator

Question Mark
A: 

This is one of those things I miss from Ruby. You can also do:

$foo = empty($foo) ? "default" : $foo;

Ugly as hell though.

hobodave
A: 

Thanks guys! All of these responses were helpful (I had read the Variables section of the docs and didn't find empty() referenced there).

I ended up using the "isset($x) || $x = 1" version posted in the other thread (which my prior searching didn't turn up--searching for special characters is problematic).

I was going to give everybody points but I can't seem to do that without registering, which I'm tired of doing for the 1,001 sites I frequent. ;)

Then mark an answer as accepted.
Chacha102
You do that by clicking the checkbox next to an answer you like, or that answered your question.
Chacha102