1

I have seen this question being asked many times, but I am yet confused and came across something similar condition. I am not sure if this and my context are same or not, as long as I am convinced this is a different scenario or else I might have misunderstood the explanation. O.k. here is my scenario:

$amount = isset($cost->getCostAmount()) ? $cost->getCostAmount() : 0;

Function costAmount() is dynamically added during run-time and it may or may not exist. So I need to first check if my function exists or not and rest is pretty clear. But now in this case I get a fatal error:

Fatal error: Can't use method return value in write context in ..../file.php

Now if I do something like this:

$amount = $cost->getCostAmount() ? $cost->getCostAmount() : 0;

Obviously I would get an error:

Call to undefined method: getCostAmount

if the function doesn't exist. What could be a possible solution for this? Explanation will be considered helpful.

Request: Please add an adequate comment to why the question has been downvoted so that I would be able to improve my questions, in the future.

4

4 回答 4

8

改变这个:

$amount = isset($cost->getCostAmount()) ? $cost->getCostAmount() : 0;

至..

$amount = method_exists($cost, 'getCostAmount') ? $cost->getCostAmount() : 0;

因为这段代码isset($cost->getCostAmount())正在执行方法getCostAmount,即使它不存在

于 2012-08-26T11:42:41.627 回答
4

isset要求您将变量传递给它而不是函数。它无法检查是否设置了返回值

你应该这样使用它,

$cost_amount = $cost->getCostAmount();
$amount = isset($cost_amount) ? $cost_amount : 0;

即使这段代码也没有意义。因为这里 $cost_amount 将始终设置。如果getCostAmount返回nullempty字符串,您应该以这种方式检查它。

$cost_amount = $cost->getCostAmount();
$amount = !is_null($cost_amount) ? $cost_amount : 0;

您的代码也找不到getCostAmount功能。如果您知道这是在某处声明的,请包含它。如果此方法是动态生成的,您可以使用method_exists.

 $amount = method_exists($cost, 'getCostAmount')? $cost->getCostAmount(): 0;
于 2012-08-26T11:47:55.367 回答
1

Try changing isset() to function_exists()

于 2012-08-26T11:38:12.763 回答
0

您可以通过以下方式 使用method_exists:(http://www.php.net/manual/en/function.method-exists.php ):

var_dump(method_exists($cost,'getCostAmount'));
于 2012-08-26T11:44:47.990 回答