GoConqr has a new look! Let us know what you think.

Notes

PHP - Exemplos Melhoria de Código

Vinícius Rezendrix PHP Portuguese 1 page

Content of the notes (1)

Page 1

Evite Variáveis Temporárias

Evitando variáveis temporárias

Sem variáveis temporárias nós evitamos ter um if local o qual pode gerar um resultado indesejado.

function isPositive(int $number) {

if ($number > 0) {

$status = true;

} else {

$status = false;

}

return $status;

}

Nós podemos remover a variável temporária retornando diretamente o status:

function isPositive(int $number) {

if ($number > 0) {

return true;

}

return false;

}

A última refatoração remove o if e finalmente temos o padrão funcional.

function isPositive(int $number) {

return $number > 0 ;

}

Nunca use funções dentro de loops

Never Use Functions inside Loops

I have seen many programmers who tend to make the mistake of using functions inside of loops. If you are doing this intentionally and is ready to compromise performance just for the sake of saving a line of code, then you certainly need to think once again.

Bad Practice:

for ($i = 0, $i <= count($array); $i++)

{

//statements

}

Good Practice:

$count = count($array);

for ($i = 0; $i < $count; $i++)

{

//statements

}

If you take the burden of storing the value returned by the function in a separate variable before the loop, then you would be saving enough execution time as in the first case the function will be called and executed every time the loop runs which can increase the time complexity of the program for large loops.

Strings mais rápidas

Understanding Strings in a Better Way

Take the code snippet as an example and try to guess which statement will run the fastest and which one the slowest.

Code Snippet:

$a = ‘PHP’;

print “This is my first $a program.”;

echo “This is my first $a program.”;

echo “This is my first “.$a.” program.”;

echo “This is my first ”,$a,” program.”;

Guess what, the last and the most uncommon statement of all wins the speed test. The first one obviously loses as the “print” statement is slower than “echo” statement. The third statement wins over the second one as it uses concatenation operation rather than using the variables inline.

The lesser-known last statement wins as there are no string operations being performed and is nothing other than a list of comma-separated strings.

Information

Description
Exemplos de melhoria de código para servir de base a outras situações. Criado para entender o processo de pensamento lógico no desenvolvimento de funções melhores.
Created by
Vinícius Rezendrix · Oct 2019
Updated
Oct 20, 2019
Views
12
Tags
php
Rating

Feedback

What is it about?

What do you think of the new look?

How do you like it?