News:

Bored?  Looking to kill some time?  Want to chat with other SMF users?  Join us in IRC chat or Discord

Main Menu

defining a function

Started by Aquilo, August 29, 2003, 07:37:20 PM

Previous topic - Next topic

Aquilo

I was wondering if this was a good way to call functions as you would variables, this works but under windows it returns an error thats why I used the @ with define I was just wondering if it was recommended or caused issues in scripts.
<?php
@define(BARfoo());

echo 
BAR;

function 
foo(){
return 
'foo bar';
}
?>

[Unknown]

I can't believe that works like that.

-[Unknown]

Parham

wait, i don't get it... why is that at all weird?

I mean if you can do this:


$variable = foo();
print $variable;

function foo(){
return 'foo bar';
}


why can't you define constants in the same way?

[Unknown]

I thought this was bad though!

$variable = foo();

I thought you had to do:

$variable = 'foo';

And then:
$variable();

-[Unknown]

Parham

oh wait, nevermind, i read the example wrong... that's pretty cool.  It doesn't define the constant as the function though (at least i think not), it processes the function and gets the return statement on the "define" line.

Brian Lacy

$variable = foo();

is actually better practice, IMHO, than

$variable = 'foo';
$variable();

The second example wouldn't even work in a compiled language. Its nice that you can do this in PHP, but it should be reserved for occasions when you absolutely have to use it. YaBB SE's template code calls functions stored in variables, and thats an example of an acceptable use, but other than that, $variable = foo(); is always preferable -- and probably a bit faster, too.

As for the constant issue, I too am surprised PHP will allow you to define a constant with a function call. The whole point of constants is that they are always the same, they never change in the entire course of your program. Ideally, good programming practice indicates that they should always be integers -- but even if your function's return value is an integer, I still feel thats poor practice.

[Unknown]

No, the issue is that defining BAR as foo() does not make BAR a synonym for foo(), but just defined as the result.

SMF's template system uses variable functions even less often. (although it still has to some.)

But, I agree... if it's at all possible, foo() should directly be used.

-[Unknown]

Advertisement: