php return or return null

Should a function use: return null;?

Is the latter considered bad practice or doesn’t it matter?

Whether it is bad practice shouldn’t be subjective IMHO.

php return or return null. Смотреть фото php return or return null. Смотреть картинку php return or return null. Картинка про php return or return null. Фото php return or return null

7 Answers 7

Always is a good practice to show what you’re returning.

But as a tip, the following are all equivalent:

In all cases there for var_dump(test()); will be:

php return or return null. Смотреть фото php return or return null. Смотреть картинку php return or return null. Картинка про php return or return null. Фото php return or return null

If you don’t return anything, just use return; or omit it at all at the end of the function.
If your function is usually returns something but doesn’t for some reason, return null; is the way to go.

It is just plain silly to return null if there is nothing to return. Doing return; shows intend of not actually returning anything. And makes it clear what the function does.

The fact that PHP does not have a void return type yet should not be a reason to make the intend less clear. Also note that PHP 7.1 will provide support for the void return type:

php return or return null. Смотреть фото php return or return null. Смотреть картинку php return or return null. Картинка про php return or return null. Фото php return or return null

What makes a difference is that you make use of docblocks and document the return value with the @return tag so clever IDE’s offer info here.

If you want to signal per the docblock that not-returning a value is intended, you can use void :

If you want to signal that returning NULL is intended, you can use null or NULL (depending on your code-style for uppercase PHP standard constants):

That should make the coders intention visible as by PHP this is would be always null as the factual return value.

Read on:

More details and updated information is in PeeHaa’s answer to this same question.

Источник

Better to return an empty string or null value

If I were writing the below method (for example) is it considered good practice to either:

A: return an empty string if the document didn’t exist

B: return a null value?

Having done a lot of Java, and methods in Java requiring a return type I’m under the impression it is best practice to return a consistent type, is this also the case in PHP or is it better to return a null value instead?

If it is better to return a null value, can you explain why?

5 Answers 5

PHP convention

OOP approch

Throw an exception. Also you should use a method dir_exitsts (or any other name you like) that only returns boolean (true of false). And use it before calling getDir

There really no specific rule for this. Its completely up to you.

For edge cases perhaps I’d stick with FALSE as a value to return. It’s, to my mind, a bit broken approach (check this link for the truly maddening example), but at least it’s a common idiom in PHP.

file_exists return FALSE for to non-existing files.

so you can change your condition with this way

alternative : is_readable

this returns TRUE if the file or directory specified by filename exists and is readable, FALSE otherwise.

php return or return null. Смотреть фото php return or return null. Смотреть картинку php return or return null. Картинка про php return or return null. Фото php return or return null

There are two popular return values for this: false or null

However, in many cases, the code that receives this return value can’t do anything meaningful with it; this is when you can throw exceptions to skip that code segment, just like in Java; it’s a convenient flow control mechanism for error handling.

Источник

PHP Exceptions VS Return usage in Functions (best practice)

In our team we often discuss the usage of exceptions inside a function VS some kind of return arrays, but I’m still not sure how to do it the right way. So let’s try to ask the question from scratch:

When to use an exception VS returning an array, containing all information about the result?

Example #1

Example 2

So which version is the «better» way of error handling, #1 or #2? Is it just a matter of taste or are there real arguments for one of the two versions?

There is one simple best practice «rule» for methods or functions which tells you to have single exit points in functions. Is this already the answer, which means it would be v2?

I’d really appreciate all thoughts about this topic 🙂

2 Answers 2

Years ago, when I read about it, I got a lot of information about the problem. First of all, the principle ‘Tell, Don’t Ask’ (here and here) and after the entire Chapter 3 and 7 from Clean Code By Robert C. Martin.

With this, you can realize some good kinds of stuff to understand what the method should and shouldn’t do.

A method should return only, and just only, when ask or asked for something. Methods asking something has the prefix as:

or, can has the word return (not necessary as prefix):

The name create is an exception, because create not necessary has to return something:

If your method doesn’t have anything of this, it shouldn’t return anything.

Inside the chapter 3, you can find the part called «Prefer Exceptions to Returning Error Codes» and inside chapter 7 you can find «Don’t Return Null». That explains about some problems created from returning something. A lot of validations chain, null object, etc. These problems can be solved just returning an exception.

Your second example is good, but like the method name says, it does awesome stuff, shouldn’t return. If there isn’t an exception, it did the awesome stuff. If the return is really necessary, you have to refactor or at least rename your method to match with is expected.

After all, it’s just a lot of suggestion to guide your coding, not an inflexible rule.

Источник

Новый PHP, часть 1: Return types

php return or return null. Смотреть фото php return or return null. Смотреть картинку php return or return null. Картинка про php return or return null. Фото php return or return nullКаждый мажорный релиз PHP добавляет ряд новых возможностей, некоторые из которых действительно имеют значение. Для PHP 5.3 — это были пространства имен и анонимные функции. Для PHP 5.4 — трейты. Для PHP 5.5 — генераторы. Для 5.6 — списки аргументов переменной длины.

PHP 7 имеет большое количество новшеств и улучшений, делающих жизнь разработчика легче. Но я считаю, что самым важным и долгосрочным изменением является работа с типами. Совокупность новых фич изменит взгляд на PHP разработку в лучшую сторону.

Почему поддержка строгой типизации так важна? Она предоставляет программе — компилятору или рантайму и другим разработчикам ценную информацию о том, что вы пытались сделать, без необходимости исполнять код. Это дает три типа преимуществ:

Возвращаемые типы

Первым дополнением к уже существующей системе типизации будет поддержка возвращаемых типов. Теперь можно указывать в функциях и методах тип возвращаемого значения в явном виде. Рассмотрим следующий пример:

Постфиксный синтаксис для возвращаемых типов может показаться странным для разработчиков, привыкших к C/C++ или Java. Однако, на практике подход с префиксным объявлением не подходит для PHP, т.к. перед именем функции может идти множество ключевых слов. Во избежание проблем с парсером PHP выбрал путь схожий с Go, Rust и Scala.

А теперь создадим наш репозиторий. (В качестве заглушки добавим фиктивные данные прямо в конструктор, но на практике, конечно же, необходимо иметь источник данных для нашего репозитория).

Большинство читателей быстро заметит, что `findById()` имеет баг, т.к. в случае, если мы попросим несуществующий идентификатор сотрудника PHP будет возвращать `null` и наш вызов `getAddress()` умрет с ошибкой «method called on non-object». Но на самом деле ошибка не там. Она заключается в том, что `findById()` должен возвращать сотрудника. Мы указываем возвращаемый тип `Employee`, чтобы было ясно чья это ошибка.

Что же делать, если действительно нет такого сотрудника? Есть два варианта: первый — исключение; если мы не можем вернуть то, что мы обещаем — это повод для особой обработки за пределами нормального течения кода. Другой — указание интерфейса, имплементация которого и будет возвращена (в том числе и «пустая»). Таким образом, оставшаяся часть кода будет работать и мы сможем контролировать происходящее в «пустых» случаях.

Выбор подхода зависит от варианта использования и также определяется рамками недопустимости последствий в случае невозвращения правильного типа. В случае репозитория, я бы поспорил с выбором в пользу исключений, поскольку шансы попасть именно в такую ситуацию минимальны, а работа через исключения является довольно дорогостоящей по производительности. Если бы мы имели дело со скалярной переменной, то обработка «пустого значения» было бы приемлемым выбором. Модифицируем наш код соответственно (для краткости показаны только измененные части):

Теперь getStreet() будет отдавать хорошее пустое значение.

Одно важное примечание о возвращаемых типах: при наследовании тип не может быть изменен, даже нельзя сделать его более конкретным (подклассом, например). Причина в особенностях ленивой загрузки PHP.

Возвращаемые типы являются большой, но далеко не единственной новой особенностью, расширяющей систему типов PHP. Во второй части мы рассмотрим другое, пожалуй даже более важное изменение: декларирование скалярных типов.

Источник

In php, should I return false, null, or an empty array in a method that would usually return an array?

I’ve found several responses to this, but none pertaining to PHP (which is an extremely weak typed language):

With regards to PHP, is it appropriate to return false, null, or an empty array in a method that would usually return an array, but has a failure occur?

In other words, if another developer jumped in on my project, what would they expect to see?

8 Answers 8

I would strongly discourage to return mixed type return values. I consider it to be so much a problem, that i wrote a small article about not returning mixed typed values.

To answer your question, return an empty array. Below you can find a small example, why returning other values can cause problems:

Hope this helps preventing some misunderstandings.

Just speaking for myself, I normally prefer to return an empty array, because if the function always returns an array, it’s safe to use it with PHP’s array functions and foreach (they’ll accept empty arrays). If you return null or false, then you’ll have to check the type of the result before passing it to an array function.

If you need to distinguish between the case where the method executed correctly but didn’t find any results, and the case where an error occurred in the method, then that’s where exceptions come in. In the former case it’s safe to return an empty array. In the latter simply returning an empty array is insufficient to notify you of the fact an error occurred. However if you return something other than an array then you’ll have to deal with that in the calling code. Throwing an exception lets you handle errors elsewhere in an appropriate error handler and lets you attach a message and a code to the exception to describe why the failure happened.

The below pseudo-code will simply return an empty array if we don’t find anything of interest. However, if something goes wrong when processing the list of things we got back then an exception is thrown.

php return or return null. Смотреть фото php return or return null. Смотреть картинку php return or return null. Картинка про php return or return null. Фото php return or return null

Here’s a modern answer that’s been valid since the 1960’s probably.

Since PHP version 4, huge efforts have been made by PHP core developers to gradually improve the PHP language. Many things remain, because we still want to have some backward compatability.

DON’T return false on error

false has always been the wrong value to return for errors. The reason you still see it in PHP documentation, is because of backward compatability.

If your function is supposed to return something other than booleans, then you force yourself to write code to handle type checking. Since many people don’t do type checking, the PHP opcode compiler is also forced to write opcodes that does type checking as well. You get double type checking!

You may return null

Optimally for the computer/CPU is that the entire value is located in a single 1, 2, 4 or 8 byte memory «cell». These value sizes are common for all native value types.

You may return a special value depending on type

This is not ideal, because

You should throw exceptions

Exceptions match the inner workings of most CPUs. They have a dedicated internal flag to declare that an exceptional event occurred.

It is highly efficient, and even if it wasn’t we have gigantic benefits of not having a lot of extra work in the normal non-erroneous situation.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *