Hello all,
I’m facing the following problem:
I have a class that, on several of is methods, will use a redirect functionality.
A simple
header("Location: ".$redireciona."");
can work but, not always, so I’m having this function for doing so:
function redirecciona($pURL)
{
if (strlen($pURL) > 0)
{
if (headers_sent())
{
echo "<script>document.location.href='".$pURL."';</script>\
";
}
else
{
//the space of : is important! cf. HTTP/1.1 standard, section 4.2
header("Location: " . $pURL);
}
exit();
}
}
Even if optional, I will need to call this function on several methods (if not all) of this class.
How should we relate this function with the class that needs to run it ?
Thanks a lot,
Márcio
I’m not. I’m using a MVWC where W stands for weird. So, nothing to be proud of.
I don’t have a controller class, but I do have a php file that communicates with the DAO side, and the “php form side” - WView (weird view) ;).
I can put the function there but then I need a way to connect the function with the specific class methods…
So, probably, this is not the best option on my case.
rpkamp:
You could make it a static function so you can call it from anywhere
static function redirecciona($pURL)
{
if (strlen($pURL) > 0)
{
if (headers_sent())
{
echo "<script>document.location.href='".$pURL."';</script>\
";
}
else
{
//the space of : is important! cf. HTTP/1.1 standard, section 4.2
header("Location: " . $pURL);
}
exit();
}
}
Supposing the name of the class is Fn (short for “functions”), you can do
Fn::redirecciona('/some/new/url');
All you need to do is include the class. There is no need to create an instance of the class to call the static function.
If, in the future, I need one more function, I can added to this “special case” class.
Question: What should we called? On what folder should we put them? One called Helper?
In the same class I see no point as well, but in another class, that we can use to call more static methods, seems nice at my first-newbie-not-at-all-expert eyes.
Thanks in advance,
Márcio
You could make it a static function so you can call it from anywhere
static function redirecciona($pURL)
{
if (strlen($pURL) > 0)
{
if (headers_sent())
{
echo "<script>document.location.href='".$pURL."';</script>\
";
}
else
{
//the space of : is important! cf. HTTP/1.1 standard, section 4.2
header("Location: " . $pURL);
}
exit();
}
}
Supposing the name of the class is Fn (short for “functions”), you can do
Fn::redirecciona('/some/new/url');
All you need to do is include the class. There is no need to create an instance of the class to call the static function.
More info can be found in the manual on the static keyword .
TomB
June 4, 2010, 3:23pm
4
What’s the point in making it a static function inside the class? Why not leave it as normal function?
Assuming you’re using MVC, you could put it in your base controller class, that way it’s accessible from all your controllers.