开发者

How to use member functions in an if statement in PHP

开发者 https://www.devze.com 2023-02-24 23:12 出处:网络
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开发者_开发知识库.

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?


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.


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


try this:

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


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


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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号