0

What is the benefit of checking first if the variable is not empty before checking the value? Is it a speed improvement?

Is it a best practice to always check it like this in php?

$_attributeType = $block->getAtType();
if ($_attributeType && $_attributeType == 'text') {
...
}

4 Answers 4

3

No, it's not best practices. We ask developer to write code like this in strict manner $_attributeType === 'value'

1
0

@Claudiu Creanga I think the developer was just trying to exercise defensive programming. One would have to install the Vulcan Debugger ( https://github.com/derickr/vld ) to monitor opcode execution to see if checking if a variable is null or not is faster than loosely comparing a variable's value with a string. The developer could have gotten away with @KAndy's code sample as being the condition within the IF statement.

0

That specific example doesn't make much sense. The two checks are indeed redundant.

That would not be the case if it were tightened up. If you're calling an object method, you need to be absolutely certain that you actually have an object first, or else you'll end up with an error (call to member function on a non-object). For instance:

if ($block && $block->getAtType() == 'text') {
...
}

That makes sure $block is not false or null before trying to call getAtType() on it.

Note that it's better to check the type as well, if you know what type it should be.

if ($block instanceof \Magento\Framework\View\Element\BlockInterface
    && $block->getAtType() == 'text') {
...
}
0

Highly speed work is this

if ($_attributeType = $block->getAtType() == 'text') {
...
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.