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

Recommended Answers

All 3 Replies

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!";
    }
}
?>
commented: Thanks for the tip +3

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() {
   ...

 }
}
commented: Thanks for the tip +3

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.