This php returns null

Должна ли функция использовать: return null ;?

Является ли последнее плохой практикой или не имеет значения? PS Является ли это плохой практикой, не должно быть субъективным ИМХО.

Если у вас есть практика указать, что null значение означает что-то конкретное, то есть аргументы функции содержат неверные данные — тогда продолжайте. Но часто логическое возвращение более чем достаточно. Я использую значение null в анонимных функциях, которые, как ожидается, будут возвращать фактические данные, поэтому логическое значение false считается приемлемым, а значение null — нет.

Мы можем сделать вывод, что это избыточно, поскольку среда выполнения уже делает это. Но это не делает это плохим или бесполезным. Ответ очевиден. Что еще интереснее, разве вы не должны писать NULL ?

@PeeHaa: Да, я считаю, что заглавные буквы — это канонический токен. И возвращаясь к ясности, это имеет больший эффект объявления.

7 ответов

Если вы ничего не вернете, просто используйте return; или опустите его вообще в конце функции.
Если ваша функция обычно возвращает что-то, но не по какой-либо причине, return null; — это путь.

Читайте также:  Create new dictionary python

Это похоже на то, как вы это делаете, например. в C: Если ваша функция не возвращает вещи, она void , в противном случае она часто возвращает либо действительный указатель, либо NULL.

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

Если нет никакой документации, мне трудно сказать. Что ты читаешь первым? Последняя строка тела функции или документы с возвращаемым типом прямо в ее голове?

Не каждая функция что-то возвращает. Или код должен четко документировать, что NULL должен быть возвращен тем, кто не говорит на этом языке? Хорошо, я вижу, что ответ изменился, поэтому я думаю, что это понятно.

Всегда хорошая практика, чтобы показать, что вы возвращаете.

Но в качестве подсказки все эквивалентны:

function test() < return null; >function test() < return; >function test()

Во всех случаях для var_dump(test()); будет:

В последнем примере функции очень ясно сказано, что возвращать нечего. Итак, какой пример показывает лучше всего на ваш взгляд?

Как и в первом комментарии . Всегда хорошая практика, чтобы показать, что вы возвращаете. Так что мой выбор — первый.

Итак, сначала вы показываете, что возвращаете что-то, а затем заканчиваете предложение, чтобы сказать, что это что-то NULL вместо того, чтобы делать меньше слов и, следовательно, заявлять очевидное?

Я бы пошел со следующим подходом для семантического осмысленного программирования: dereuromark.de/2015/10/05/return-null-vs-return-void

Значение возвращаемой функции undefined в PHP всегда равно NULL , поэтому это не имеет никакого значения (время выполнения делает это).

Что имеет значение, так это то, что вы используете docblocks и документируете возвращаемое значение с тегом @return , поэтому здесь есть умная информация о IDE.

Если вы хотите сигнализировать на док-блок, что не возвращается значение, вы можете использовать void :

Если вы хотите сообщить, что для возврата NULL вы можете использовать NULL или NULL (в зависимости от вашего стиля кода для стандартных констант PHP):

Это должно сделать видимость кодеров видимой, так как PHP это всегда будет NULL как фактическое возвращаемое значение.

Читайте дальше:

Более подробная информация и обновленная информация в PeeHaa отвечают на этот же вопрос.

Просто глупо возвращать null , если ничего не вернуть. Выполнение return; показывает, что на самом деле ничего не возвращает. И дает понять, что делает функция.

Тот факт, что PHP не имеет типа возврата void еще не должен быть причиной, чтобы сделать наступление менее ясным. Также обратите внимание, что PHP 7.1 обеспечит поддержку типа возврата void :

Семантически, я не думаю, что есть разница между ними. Согласно документации PHP по возврату:

Если параметр не указан, то круглые скобки должны быть опущены и NULL будет возвращен.

Мне лично нравится помещать туда NULL. Тогда нет вопроса о том, что возвращается, что облегчает вашу отладку.

Это правда. Мне просто нравится быть многословным, я думаю. Когда я смотрю свой код спустя 1 год, поздно ночью, пытаясь выяснить, что сломано, мне нравится иметь все перед собой (ничего не подразумевается). Личное предпочтение.

Когда вы используете декларации возвращаемого типа с префиксом nullable «?» есть разница!

Начиная с PHP 7.1.0, возвращаемые значения могут быть помечены как обнуляемые, если перед именем типа ставить знак вопроса (?). Это означает, что функция возвращает либо указанный тип, либо NULL.

Таким образом, когда вы ничего не возвращаете, сообщение об ошибке будет:

Fatal error: Uncaught TypeError: Return value of test() must be of the type string or null, none returned in.

И когда вы вернетесь, return; сообщение об ошибке будет:

Fatal error: A function with return type must return a value (did you mean «return null;» instead of «return;»?) in.

Когда вы возвращаете null , все в порядке.

Источник

$this PHP returns null

Just wondering why the get method returns Null

class Test < protected $title; public function setTitle($ttl) < $this->title = $ttl; > public function getTitle() < var_dump($this->title); return Null . return (string) $this->title; > 
$test = new Test(); $test->setTitle('ttl'); 

get Method in Controller 2

$test->getTitle(); return Null 

Answer

Solution:

If you want to use the getTitle(); in another controller, then you need to export your object from the first controller. Because that’s how OOP works.
If you create in a file something like this:

$title= new Title(); $title->setTitle('tlt'); 
$title = new Title(); $title->getTitle('tlt'); 

You’ll get NULL . This is because the $title from the first Controller isn’t the same object with the $title from the second controller.

Try to use a function to export your object: try this in the first controller

function exports()< $title= new Title(); $title->setTitle('tlt'); return $title > 
$title = exports(); $title->getTitle(); 

Share solution ↓

Additional Information:

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Similar questions

Find the answer in similar questions on our website.

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

About the technologies asked in this question

PHP

PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/

Welcome to programmierfrage.com

programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.

Get answers to specific questions

Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.

Help Others Solve Their Issues

Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.

Источник

$this PHP returns null

Just wondering why the get method returns Null

class Test < protected $title; public function setTitle($ttl) < $this->title = $ttl; > public function getTitle() < var_dump($this->title); return Null . return (string) $this->title; > 
$test = new Test(); $test->setTitle('ttl'); 

get Method in Controller 2

$test->getTitle(); return Null 

Answer

Solution:

If you want to use the getTitle(); in another controller, then you need to export your object from the first controller. Because that’s how OOP works.
If you create in a file something like this:

$title= new Title(); $title->setTitle('tlt'); 
$title = new Title(); $title->getTitle('tlt'); 

You’ll get NULL . This is because the $title from the first Controller isn’t the same object with the $title from the second controller.

Try to use a function to export your object: try this in the first controller

function exports()< $title= new Title(); $title->setTitle('tlt'); return $title > 
$title = exports(); $title->getTitle(); 

Share

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Similar questions

Find the answer in similar questions on our website.

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

About the technologies asked in this question

PHP

PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/

Welcome to webdevask.com

Welcome to webdevask.com

Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.

Get answers to specific questions

Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.

Help Others Solve Their Issues

Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.

Источник

Оцените статью