Jimmy P
Jimmy P

Reputation: 1892

PHP: Check for existence and declare function in one line

Is there a way to check if a function exists already, and then declare it in the same line if it doesn't, without using if?

I'm aware that it's possible to do

if (!function_exists('func')) function func() {}

but for academic reasons I'm curious if there are different ways to do that. Perhaps something along the lines of

function_exists('func') or function func() {}

or

(function_exists('func') ? '' : function func() {})

but actually works?

It seems that you can actually declare an anonymous function using the first syntax:

function_exists('func') or function() {}

but that's no good because the function doesn't have a name...

And it's also possible to assign the function to a variable,

function_exists('func') or $func = function() {};

but the function isn't in the global scope doing it that way.

Upvotes: 1

Views: 1946

Answers (2)

Alkarin
Alkarin

Reputation: 464

Considering all PHP functions are declared globally, it escapes me why you'd have to check if a function already exists or not (or why it must be checked without using an if statement).

Unless of course you have it declared in some other php file that is not included on your current page assuming you are building a web application.

However there is a a php function that checks if a function exists, but depending on your logic you'd still have to use some sort of if statement.

if (!function_exists('my_function')) {
    //delcare function...
}

To answer your question: No. There's not really a way to do this other than as you described, simply because there is no reason to do it any other way.

Upvotes: 1

Machavity
Machavity

Reputation: 31654

The only other way I can think of to do this is to have func() declared in an include

function_exists('func') or include('func.php');

Of course, if it's in an include, you can do it much more simply by doing it like this

include_once('func.php');

Upvotes: 2

Related Questions