Page 1 of 1
silly function question
Posted: Thu Sep 13, 2007 5:02 am
by panic!
I was wondering if there's a way to see within a function if when it was called it was expected to return a value.
So for example
Code: Select all
function some_function(){
$a=$a+100;
// if it was expected to return a value then return a value..if not print the value
if (something) {
return $a;
}else{
print $a;
}
}
$a=some_function(); //this returns the value into a
some_function(); // this prints the value
Posted: Thu Sep 13, 2007 5:27 am
by Mordred
1. You can't.
2. You shouldn't want to.
3. Okay, if you really must, you can, pass a boolean parameter.
4. But really, don't, it's bad karma.
Posted: Thu Sep 13, 2007 5:30 am
by panic!
yeah I was thinking of passing a paramater but it seems silly.
Why is it bad practice out of interest.
Basically I've made a helper for creating hyperlinks (a la codeigniter/RoR) and I'd like to print the hyperlinks if it is simply called and return the hyperlinks if it is assigned to a variable. because sometimes I might want to return the a hyperlinks that is created to pass it into another helper.
Posted: Thu Sep 13, 2007 6:01 am
by Mordred
1. (stupid)
Code: Select all
function PrintLink($sUrl, $sText) {
echo "<a href='$sUrl'>$sText</a>";
}
function ReturnLink($sUrl, $sText) {
return "<a href='$sUrl'>$sText</a>";
}
PrintLink('http://google.com', 'google');
$sLink = ReturnLink('http://google.com', 'google');
2. (a bit wiser)
Code: Select all
function ReturnLink($sUrl, $sText) {
return "<a href='$sUrl'>$sText</a>";
}
function PrintLink($sUrl, $sText) {
echo ReturnLink($sUrl, $sText); //code reuse!
}
PrintLink('http://google.com', 'google');
$sLink = ReturnLink('http://google.com', 'google');
3. (a lot wiser)
Code: Select all
function MakeLink($sUrl, $sText) {
return "<a href='$sUrl'>$sText</a>";
}
echo MakeLink('http://google.com', 'google');
$sLink = MakeLink('http://google.com', 'google');
Not hard, innit?
Reply
Posted: Thu Sep 13, 2007 8:54 am
by user___
Hi guys,
This is just a suggestion and in my opinion it will be better.
Mordred:Why do not replace the last lines in that way:
Code: Select all
$sLink = MakeLink('http://google.com', 'google');
echo $sLink;
In that way the code works faster and it is cleaner.
Re: Reply
Posted: Thu Sep 13, 2007 11:16 am
by John Cartwright
user___ wrote:Hi guys,
This is just a suggestion and in my opinion it will be better.
Mordred:Why do not replace the last lines in that way:
Code: Select all
$sLink = MakeLink('http://google.com', 'google');
echo $sLink;
In that way the code works faster and it is cleaner.
He was just showing the possibility of echo'ing the return or storing it's value in a variable
