user455318
user455318

Reputation: 3346

How to use member functions in an if statement in PHP

If I have a function called name(), I can check if (name()) {}, and if name() evaluates to true then the body of the if is executed.

But with a class like this:

$miniaturas = new miniaturas();
$miniaturas->thumb($db);

If I try:

if (thumb($miniaturas->thumb($db))) { }

Or this:

if (thumb($db)) {}

I get:

Fatal error: Call to undefined function thumb() .

How can I call this function in a class like I do for functions outside a class?

Upvotes: 2

Views: 258

Answers (6)

user56581111
user56581111

Reputation: 11

i think you want if ($miniaturas->thumb($db)) { // code } and the method thumb should return a boolean

Upvotes: 1

rmoorman
rmoorman

Reputation: 309

in addition to the comment from Neal, the I check for method/function existance using the following php builtin functions:

  1. function_exists: I use this one to see if a plain function exists

    if (function_exists('thumb')) { thumb($db); }

  2. method_exists: I prefer to use that one if I have to check for "methods" of objects

    $miniaturas = new miniaturas();

    if (method_exists($miniaturas, 'thumb')) { $miniaturas->thumb($db); }

In addition to that you also can use is_callable, which checks whether a function/method is callable ... take a look at

doc for function_exists

doc for method_exists

doc for is_callable

Upvotes: 1

Michael
Michael

Reputation: 35341

The function_exists() function is used to determine whether or not a function exists:

if (function_exists('thumb')){
  //...
}

Upvotes: 0

Naftali
Naftali

Reputation: 146310

try this:

if(function_exists("$miniaturas->thumb"))

Upvotes: 1

preinheimer
preinheimer

Reputation: 3722

if (thumb($miniaturas->thumb($db))) {}

Unless you actually have a function named thumb you want

if ($miniaturas->thumb($db)) {}

The extra function call to thumb is what is breaking

Upvotes: 1

Jimmy Sawczuk
Jimmy Sawczuk

Reputation: 13614

It's just if ($miniaturas->thumb($db)) { ... }. This is because you defined thumb() as a member function to the class miniaturas, and because it's a member of that class it's not a member of the global namespace.

Upvotes: 5

Related Questions