Author - StudySection Post Views - 130 views
php

Tips for improving PHP code

Problem 1: Not using PHP built-in function

Sometimes we try to solve the small problem with our own function instead of a built-in PHP function that provides the functionality.

Solution:
PHP provides many useful functions that remove the need to “refresh the wheel”, and will often complete the work much better than anything typed by a standard program. Therefore, if you are experiencing the need to write complex tasks that you think may already exist, it is best to search the Internet (and PHP scripts in particular) before you start writing your code.

Problem 2: Using Magic Numbers and Strings

A magic number is a number in code which does not have any explanation and name. For example: in the following code, 10 is a magic number:

<?php
for($i=1; $i<10; $i++) { //code; }

In this code, it is not clear why it will execute 10 times.

Solution:
To make it meaningful and readable we can give the variable with a useful name. For example:
<?php
$checks=10;
for($i=1; $i<$checks; $i++) { //your code; }

Similarly, magic strings are the strings in the code which do not have any explanation. In this case also, it is recommended to set a meaningful name for a variable.

Problem 3: Not creating functions

Not creating functions is a typical problem for developers mainly for beginners. The problem stems from the fact that a programmer can write multiple lines of PHP scripts without having to encrypt parts of the code into tasks. This is problematic because it is difficult to understand what the code actually does without going deeper into it, and the developer may repeat himself unintentionally.

Solution:
Dividing the functions into small individual functions is a good solution to this problem.

Problem 4: Code Duplication

If you are writing the same code more than one or two times then there will be something wrong with the code. In this way you are violating the important rule of modern code writing: Do not Repeat Yourself (DRY). This is important because if the code is finished and one code is written more than one time and after that, if there need to make changes, then you have to make more efforts to make changes in all the places.

Solution:
Wrap the code in a function is a good way to avoid duplication. Then the function can be called whenever needed.

Problem 5: Functions that do more than one thing

An effective function can do only one job and it can be called from different places in the code because it is ideal and performs a specific functioning for which task it is created.
function phone_number($number)
{
$digits = preg_replace('/[^0-9]/','',$number);
$len = strlen($digits);
$isValidPhoneNumber = ($len >= 7 && $len <= 14); if(!$isValidPhoneNumber) $digits = "Not a phone number"; // return the phone number wrapped in html return "<p>{$digits}</p>";
}
var_dump(phone_number("1-800-123-4567"));
var_dump(phone_number("1-800-123-45678910"));

Answer is

string '<p>18001234567</p>' (length=18)
string '<p>Not a phone number</p>' (length=25)

As we can see, the function validates the phone number and then wraps the result in HTML. This means that we cannot use the function every time we want to check the validity of a phone number because it does not return a boolean (true or false) value, but returns HTML. The effect is serious because we have to repeat ourselves and rewrite the authentication code repeatedly in each application which requires checking the validity of a phone number.

Solution:- Write down the code into a separate function. The first is check validation and the second is wrap in HTML.
function validate_Phone_Number($string)
{
//replace all the non-digit characters
$onlyDigits = preg_replace('/[^0-9]/','',$string);
// check if the remaining string is 7-14 characters long and return boolean (true/false) value
$onlyDigitsLen = strlen($onlyDigits);
return $isValidPhoneNumber = ($onlyDigitsLen >= 7 && $onlyDigitsLen <= 14); } function wrapInHtml($string) { // return the string wrapped in html return "<p>{$string}</p>";
}
// check the two functions
$string = "1-800-123-4567";
$isValidPhoneNumber = validate_Phone_Number($string);
var_dump(($isValidPhoneNumber)? wrapInHtml($string) : wrapInHtml("Not a valid phone number"));

Problem 6: Too many nested conditions

Many times, the use of nested conditions (like nested if-else condition) makes the code disorganized and difficult to read.

Example:
$code==='z';
if($code==='a' || $code==='b')
{
if($code==='a')
{
echo "a";
}
if($code==='b')
{
echo "b";
}
}
else
{
echo "empty";
}

Answer: empty

Solution:
This problem can be solved with the use of function and return statement in the code. For example:
function removeNested($code)
{
if($code==='a') return "a";
if($code==='b') return "b";
return "empty";
}
$code = "z";
echo removeNested($code);

Problem 7: Vague names for functions and variables

Another problem that seems to exist even within the experienced system is that of the fixed and unambiguous words that do not change variables and function. For example, a job name like "doSomething" is not very clear. The problem may be due to a number of reasons: a lack of awareness, laziness, or the result of an activity that was written to perform a particular action, but which ended up taking another action instead. It creates the problem of readability of the code and makes it difficult in maintaining and making changes in the code.

Solution:
The solution is to assign an illustrative word that contains 2 to 3 words or more to function and variable names.

Get certification for your knowledge in the fundamentals of Computer functioning by clearing the Computer Certification Examconducted by StudySection. After going through this Computer Certification exam, you will be able to evaluate your basic knowledge of computers.

Leave a Reply

Your email address will not be published.