0

Hi all,

I have seen code of the form:

if(file_exists("foo.php")
  include("foo.php");
else
  include("blah.php");

As far as I know, this is perfectly legal in php. What I was wondering was is it possible to do the following in in-line code in PHP?

if(file_exists("foo.php")
  // contains a specialised version of myFoo function
  include("foo.php");
else
{
  // define the default function here
  function myFoo($param)
  {
      // do something here
  }
}

So in other words I want to be able to define a function in my PHP code only if the specialised version does not exist. I need to do this without the use of classes and inheritance if possible, and I can't include a second file at this stage, just wondering if the above code is legal or not.

Thanks in advance for your thoughts and time.

Regards,
darkagn

3
Contributors
3
Replies
5
Views
7 Years
Discussion Span
Last Post by darkagn
1

It should be, yes. You can define functions and classes withing an if block if you need to.

Doing something like this is pretty common:

<?php
if(!function_exists('myFoo')) {
    function myFoo() {
        echo "My Default Foo!";
    }
}
?>

Edited by Atli: Added the example.

Votes + Comments
Thanks for the tip
1

That should work fine. I have done this sort of thing to prevent a double definition of a function as in:

if (!function_exists('abc')) {
 function abc() {
   ...

 }
}

Edited by chrishea: n/a

Votes + Comments
Thanks for the tip
0

Thank you both for the advice, I didn't know about the function_exists function. That's a great tip :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.