anastasionico

anastasionico.uk

Construct and Comments of PHP 7

You have read about them when you opened your first programming book

You have written them thousands of times,

You are going to use them tomorrow and 5 years from now,

What are they?

PHP constructs!

These are the fundamental of the knowledge, the core of the language,

I know what you are thinking at this moment:

“Come on now, I have been a developer for a long time and now I am here to read about constructs?”

Just read throughout the post,

I guarantee you that you will find not one but several little details that even if you have coded for a long time you do not know already.

Introduction of PHP construct

There is a big difference between PHP functions and constructs,

The firsts, are mapped and then simplified to become a set of PHP constructs that are parsed, the latter cannot be used as callback but they are understood directly by the parser.

Construct also observe different rules when comes to parameters and parentheses.

Here is an example:

echo “Hello World”; 
echo “Hello”, ”World”;
echo(“Hello”,”World”);

I am sure you have already seen echo before anyway, these above are several variations of the echo construct.

Notice that the last statement will throw a syntax error.

There are a dozen constructs provided by PHP.

Their functionalities run in the background and in the majority of the case, like when you work on arrays, they are faster than the code you create yourself.

Below you will find a complete list of the most used construct in PHP 7,

You do not need to learn them by heart, you will realize that after a while they will become second nature,

You may consider this part of the series as a note that you can consult any time you are in doubt or you need to.

By the way, this is the second part of a series “PHP basics for Expert developer”.

If you haven’t already,

have a look at the other parts 
 The renaissance of PHP 
 How to use variables (PHP 7)

Table of content:

assert()

This construct takes two parameters, the first is an assertion the second is a message that needs to be shown if the assertion is false.

You can use this control to vary the flow of the script;

assert('2 < 1', 'Two is less than one');

array()

Very simple to understand, this language construct is used to create arrays.

$capricciosa = array('tomato sauce', 'mozzarella', 'artichoke', 'mushrooms', 'anchovies');

Have a look at the official manual

declare

This construct is endangered,

You will rarely come across it in codes because a handful of programmers know about its existence and even less know how to use it properly.

Declare’s syntax is similar to other flow control construct.

There is the keyword declare that is a directive inside parenthesis and the code to be executed inside brackets.

Unlike if statement that gives you freedom on the condition inside a declare there are only three possible options thicks, encoding and strict_type.

Ticks

During the execution of a PHP script, several statements are being executed,

Most of this statement causes a tick,

Using declare(ticks = number) and the related function register_tick_function(), you can execute code in between these ticks.

Declare sets how many statements should pass whereas the register_tick_function() specify which function should be called in case of a tick.

This may be useful in loops or testing.

function hyphen(){ 
echo "-";
}
register_tick_function("hyphen");
$i = 0;
declare(ticks = 4) {
while ($i < 17)
echo "n"; ++$i;
}
// the previous code echoes: nnnn-nnnn-nnnn-nnnn

As you can see I have just created a string that works as a placeholder for credit and debit cards.

Very easy.

Encoding

Another condition,

Here the code is executed only in case the encoding corresponds of the one defined

declare(encoding='ISO-8859-1');
// code goes here

Strict type

When possible PHP values a wrong type into an expected scalar type.

For example:

x = "10" + 10;
// x = 20;

PHP is smart enough to understand that the string with “10” meant to be an integer and sum the number without any problem.

Now,

there will be some case in which you do not want to lose the code and you need to manage it in a stricter way.

In strict mode, only a variable of exact type is accepted, in case of variable conflict, a TypeError will be thrown.

Here is how you can define the level of control you what to have.

declare(strict_types=1);

Notice that the string above need to be the first statement of the page, just after the PHP opening tag.
 Otherwise, you will encounter this error //Fatal error: strict_types declaration must be the very first statement in the script.

die and exit

These two constructs are aliases, they terminate the program while returning a message to the script.

Curiosity: the die construct is used in a famous technique that tests variables and stops the code of your program in a precise line, this technique is called dump and die.

If you have any experience with frameworks such as Laravel you may have seen it as dd().

If you don’t here is one of the best comparisons of PHP frameworks you can find on the web in 2018 and beyond

This is the code that is being executed behind the scene:

die(var_dump($variable_to_test));

do, while, endwhile

They are loops that are executed in case a condition is verified, I am going to explain them in detail in the following post.

Subscribe to be notified when the post will be published.

echo and print

Output a value to stdout (either it is the default monitor or another device).

The reason I write this kind of tutorial is helping you to become a better programmer, thus improve in your career.

What is the difference between echo and print then?

The one above is one of the most frequently asked questions during interviews as a web developer.

The answer is that the echo construct does not return any value whereas the print construct will return a value even null,

This means that you can use print inside an expression if you need.

echo in w3schools

else, elseif, if, endif, switch, endswitch

All of them belongs to the same family,

They are used to create conditions,

stay tuned!

I will describe them in details in future posts

empty()

This construct returns a boolean value depending on the value used a parameter.

Keep in mind that null variables, empty strings or sting with the value “0”, arrays with no values, number variables with values of 0, and false are all considered empty

endfor, endforeach, for, foreach

Other constructs that belong to the category of loops.

eval()

This construct allows the execution of PHP code given as parameter, and it is very dangerous because allows the execution of PHP code given as parameter.

No!,

you did not just have a déjà vu,

I wrote it twice because I want you to understand how problematic this can be.

PHP core team discourage its use but if you choose to use it anyway, you must pay incredible attention not to pass any user data, especially without validate it before process it.

$string = 'dog'; 
$name = 'Tommy';
$str = 'My pet is a $animal and its name is $name';
echo $str. "\n";
// the previous line echoes: My pet is a $animal and its name is $name'. eval("\$str = \"$str\";");
echo $str. "\n";
// the previous line echoes: My pet is a dog and its name is Tommy'

goto

There are no skills required in order to take a clear, well-written code and mess it up completely.

Fortunately,

if this is your goal, (really?) PHP provide the perfect keyword to use.

Goto is composed of two parts, the first is the label the second is the target,

This command permits to jump from the label to another section that would be the target bypassing every statement in between.

There are a few rules you need to keep in mind when using goto.

Both the label and the target must be in the same context, it means you cannot target code inside a method or a function.

At the same time, you cannot jump off a function invoking a target that is outside the scope

include, Include_once, require, require_once

These four constructs of PHP have the same functionality but in a slightly different way.

include, as the keyword indicate include a file and evaluates it,

include_once, this command is similar to the previous one but PHP will make sure to include the file only one time,

require, looks very similar to include, in fact, it also includes the file indicated and evaluates it but in a mandatory way,

require_once, the same thing of include once,

There is one main difference between the required and the includes ones,

And it stays on the error that is thrown if the file is not found or cannot be read.

The two include will just throw a warning whereas the required is going to generate a fatal error and you won’t be able to continue.

So,

As a general rule, if the file requested is important and the script cannot continue without I personally use require otherwise you go for include.

These constructs are less and less used because of autoloading that load automatically all the class indicated present in a script.

These are more advanced features that I have explained in my series of tutorial regarding Object-Oriented programming in PHP

If you use a PHP framework all the file are requested automatically using several types of design pattern so you do not need to worry about it.

instanceof

This construct is useful when you are coding using the Object-Oriented Paradigm.

What this constructor does is to return a boolean that indicates that the PHP variable is an object of a determinate class.

class Building { } 
class School extends Building { }
$school = new School;
var_dump($school instanceof School);
// this will dump true
var_dump($school instanceof Building);
// this will also dump true because School is a child of Building

insteadof

Traits are an OOP feature that is used to solve the limitations of the single inheritance of classes,

A trait is similar to a class, by using traits you can implement new behaviours and add functionality impossible to add otherwise.

A problem that you can encounter when using trait is that there may be a name conflict, you need to use different traits that have the same name.

The insteadof operation can be used to choose the trait you prefer.

trait def { 
public function pass() {
echo 'low';
}
public function shot() {
echo 'high';
}
}
trait att {
public function pass() {
echo 'low';
}
public function shot() {
echo 'high';
}
}

isset()

It checks if a variable has been set return true in case of positive response false if the value does not exist.

if (isset($variable)) { 
echo "$variable is set";
}

list()

This construct takes an array and a list of variables and assigns the value of the array to the multiple variables at once.

$sentence = array('fish', 'raw', 'bitter'); 
// Listing all the variables
list($dish, $temperature, $flavour) = $sentence;
echo "The $dish is $temperature and taste $flavour

Also, take note that you can read about some really interesting new features in PHP 7.3 regarding the list() construct

return

The return construct is used to stop the current script and, if required, provide the variable you want to get.

You can use return inside a function and in a global scope.

If you use it inside a function or a method it will return a variable and return to the calling scope, if instead, you use it in the global scope it will terminate the program.

For this reason, it is possible to use it inside include or required files.

unset()

This language construct takes a variable as a parameter and destroys it.

This is not always the case, in fact when you “unset” a variable you need to take count of the scope you are in.

In fact, if you destroy a variable inside a function the value will still be available on the global scope.

You can check if the variable exists or not using the isset() construct that I have explained just a few lines above

$variable = 'this is a string'; 
unset($variable); echo $variable;
// the result of the echo will be NULL

Comments

Like the majority of other programming languages even in PHP comments are a fundamental part of the language.

There are three different methods to create a comment, their origin comes from older languages.

  • C style They are one line comment and are indicated by the symbol #
  • Perl style They also are one line comment and are more common than the previous one, they are indicated by the symbols //
  • Multiline comments Those groups comment over more than one line. The block starts with /* and finishes with the opposite */

There is also an external standard mostly used for API which looks like multiline comments but with a difference:
 /** This is called API comment

*/

Comments on tutorial republic

Conclusion

Now you know all about them,

One risk for both an expert web developer and a beginner level is to get very good at using some functions and forgot about other that might do the same thing but in a slightly different way, or perhaps, doing different things that you did needed to learn long time ago but it would be necessary sometime in your near past,

I want you to shift your strategy.

Surely there are here some construct that you do not use very often,

Am I right?

Well, now you learned more about them,

Try a step-by-step approach to implement them in your code and you will see that they will easily enter into your arsenal and make you a better programmer.

After all, that is what we all really want.

have a look at the other parts 
 The renaissance of PHP 
 How to use variables (PHP 7)

More by anastasionico

Topics of interest

More Related Stories