Welcome Guest, Not a member yet? Register   Sign In
Interesting code snippet
#1

[eluser]steelaz[/eluser]
While reading someone else's code I noticed interesting code snippet (pattern? alternative syntax?). I've never seen it before, basically it looks like this:

Code:
@$a or $a = 'default value';

Granted, it will set default value even when $a is empty string, FALSE or 0, but sometimes that is exactly what you need. Alternatively, something like this can be used:

Code:
isset($a) or $a = 'default value';

What do you think? I kinda like it.
#2

[eluser]dustinsenos[/eluser]
That is a handy snippet. I was wondering how to achieve this effect with PHP. In ActionScript (and JS I'd imagine) the same functionality is:

Code:
var foo:String = bar || '';
#3

[eluser]NogDog[/eluser]
Another possibility:
Code:
$a = isset($a) ? $a : 'default value';
A little bit wordier, but some might be more comfortable with it.
#4

[eluser]TheFuzzy0ne[/eluser]
I have to say that I prefer the ternary syntax. It's clearer to me. I say if you've just seen a different way of doing things for the first time, chances are it should be avoided, as I'm sure there's a reason we haven't learnt it. If everyone adopts it, then it's probably a good thing.

I like using a function like this:
Code:
function isset_or($var, $default='')
{
    return (isset($var)) ? $var : $default;
}

$some_var = isset_or($some_var, FALSE);

Perhaps it's overcomplicating things, but I'm comfortable with that, and I think it's quite simple to follow.




Theme © iAndrew 2016 - Forum software by © MyBB