How to use PHP instructions and need instructions | Scout APM blog (2023)

How to use PHP instructions and need instructions | Scout APM blog (1) Mulco hannahon July 17, 2020

How to use PHP instructions and need instructions | Scout APM blog (2)

In the field of computer science and software engineering,ReusabilityAndModularityare regarded as important design principles that have to be taken into account when creating software programs. The main idea for these principles is to write code in a way that does not focus on all its operations in one place.to disassemble atomic parts that are independent, reusable and interchangeable. This makes it easier to debug projects, reduce redundancy, save a lot of storage and resources and thus enables more stable updates.

How to use PHP instructions and need instructions | Scout APM blog (3)

A very common example of this is on every website that you visit on the Internet. The most websites share a very common abstract structure - each website has a navigation bar (or a header), a footer and some content between the two is a usualPractice by web developers, components such as the header, the footer and many others on all sides of the website to reuse.

The virtues of reusability and modularity are not only limited to web components - we can also generate and reuse external classes, functions and variables.

In order to be able to implement such a modular setting, we must be able to include external files/modules in our code. Use different programming languages to use different options for importing modules. In this article we will see how we files in our preferred web programming languagecan import.Php.

We will learn to use PHPscontainAndrequireFunctions to include external PHP files in our code. This way we can modularize our project and reuse existing blocks from PHP code without having to copy them into our main file. We will also look at two variants of these functions -include_onceAnduniqueAnd see how you can help us prevent likely mistakes. We will discuss many examples to get a clear understanding of how these functions can be used.

Here you will find an overview of what we will cover in this article so that you can control the guide:

  • Introduce functions in PHP and request
  • PHP includes function
  • PHP contain examples
  • PHP require function
  • PHP requires an example
  • Include VS requirement
  • Prevent errors: PHP include_once and Request_once instructions
  • Conceptions

Let's begin!

Introduce functions in PHP and request

Both,containAndrequireFunctions in PHP, which are imported to import external files/modules into our code and rated at the location where they were imported. This takes place by copying the content from the external file in our main file during the term.

How to use PHP instructions and need instructions | Scout APM blog (4)

As we have discussed above, we can systematically modularize and organize our project to include files in our code to create separate files for separate components of our application and to draw everyone in our code, wherever this is necessary.that the components once created can be reused anywhere in our application, which makes maintenance easier.

Let's look at these two functions in more detail.

Note:During the rest of the article, the external file refers to the file to be contained, and the main file refers to the file containing the former.

Phpcontain

ThecontainAs an argument, the function takes the name of the file (string), which is to be included. You can call up the function with one of the two species -

Including ($ file name);

or

Include $ filename;

When we import an external file with the importcontainFunction, the statements of the external file are carried out in the line wherecontainis called.

Now let's take a look at some examples that use themcontainFunction.

PhpcontainExamples

We start with a fairly simple example -

(Video) Full APM Overview: PHP

example 1

Here we will see how the code of an external file is carried out from our main file after inclusion.

We will do this by creating a filemy_file.phpand it in an inclusiveindex.phpFile.

<?php // my_file.php echo "called by my_file.php! <br>"; $ my_string = "Hello world!";?>

Now we will include this file in our index.php file.

<!Doctype html> <!-index.php-> <html long = "en"> <body> <?Php echo "before the file is included. <br>"; close 'my_file.php'; // including file echo $ my_string;

EXIT

How to use PHP instructions and need instructions | Scout APM blog (5)

As you can see, the code from the file contained (my_file.php) was executed in the line in which the file was recorded.

Another thing that must be observed here is that if you record an external file in your code, the variable scope of your main code (in the line in which the insertion function is accessed) brought together with that of the (external) file it containswill be the variables, classes and functions in the main file (wherecontainis also mentioned) also accessible in the external file.H. variables that are declared in the external file are also accessed in their main code.

Example 2

Now we look at an example in which we can access the status of our main code from an external file when we include it.

my_file.php(External file that we will record in index.php)

<?php // my_file.php echo "contained according to the file -> <br>"; $ my_var += 5; // my_var is defined in index.php?>

index.php

<!Doctype html> <!-index.php-> <html long = "en"> <body> <?Php echo "before the file is contained-> <br>"; $ my_var = 0; // declared a variable -cho "initial value of my_var:".$ my_var."<br>"; close 'my_file.php'; echo "new value of my_var:".$ my_var."<br>";?> </body> </html>

EXIT

How to use PHP instructions and need instructions | Scout APM blog (6)

As we can see, the variable $ $my_varThat was defined inindex.phpcan be (and modified) from our external file. This shows how the variable scope of the external file (my_file.php) is from the main file (index.php).

Example 3

Now let's look at a more extensive and more practical example to understand howcontainCan help us reuse web components on a website.

If we created a basic website, we would like to record a reusable navigation bar and a footer component that would be consistent on all sides.Smaller reusable parts would serve for our website. We can then incorporate them into our index website.

So we want our website to look.

How to use PHP instructions and need instructions | Scout APM blog (7)

First let us create the children's components as such -Nav.php, CONTENT.PHP UND FOOTER.PHP.Index.php web-page structure

(Video) Elastic Search integration in laravel application

Nav.php (navigation bar)

<Div class = "nav"> <nav> <!-Use the HTML NAV day to create basic nav-bar-> <a href=""> Link 1 </a> / <a href = ""> Link 2 </a>/<a href=""> Link 3 </a>/<a href="> Link 4 </a>/</nav> </div>

content.php (arbitrary content)

<Div class = "content"> <!- Add some basic content -> <h4> Content </h4> <p> cupidatat with the exception of self -steepers, unless the next recipe. </p> <p> The outdoor will result from training time. <P> </div>

footer.php

<Div class = "footer"> <footer> <!-Use the HTML foot horny tag-> <div> I'm a footer! </div> </footer> </div>

Now that our children are ready, let us create themindex.phpFile and add them. We will also add a very simple CSS styling for presentation purposes.

index.php

<!Doctype html> <html long = "en"> <head> <styles> / * Add a basic styling * / .nav {background color: lightblue; upholstery: 1%;} .Content {background color: lightgrey; padding: 1%;} .Footer {background color: Darksagreen; upholstery: 1%;} </style> </head> <body> <?PHP # Define Names of files that are to be recorded here $ nav_filename = 'nav.php'; $ content_filename = 'content.php'; $ footeter_filename = 'Footer.php'; # including the navigation bar here $ nav_filename; echo "<hr/> ";# including content here contain $ content_filename; echo" <hr /> ";# including footer here $ footer_filename;?> </body> </html>

EXIT:

How to use PHP instructions and need instructions | Scout APM blog (8)

As you can see, we were able to successfully include the various children's components in our main file.

Similarly, these children's components (navigation foot, footer and content) can be reused on the entire website on the entire website. This is why prospective updates in one of these components, as already mentioned, only have to be made in one place instead of changes to allTo make websites that use these components.

This level of reusability and modularity ensures good coding practices and makes life easier for web developers.

Now let's take a look at the similar PHPrequireFunction.

PHP require

TherequireFunction works in the same way ascontainWith the exception of a small difference that we will discuss in the next section.

It also takes on the name of the file, which is to be recorded as an argument -

require ($ file name);

or

Need $ file name;

Let us see how it worksrequirecan be used by an example.

PhprequireExamples

In this example, we will inherit a function that is declared in an external file in our main file using Required, and then call it up.

my_file.php

<?PHP function foo ($ boo) {// function, which is to be legally angled by index.php echo "function! <br>"; $ boo += 5; return $ boo;}?>

index.php

<!Doctype html> <html long = "en"> <body> <?Php echo "before the file is included. <br>"; require 'my_file.php'; // This call inherits all code from our external file $ arg = 0; $ boo = foo ($ ark);Function Echo "Function returned ->".$ boo;?> </body> </html>

EXIT:

How to use PHP instructions and need instructions | Scout APM blog (9)

(Video) What is APM (Application Performance Monitoring).mp4

In the example above, we saw how we were able to perform a function defined in an external file from our main file.

Include VS requirement

As you can see,containAndrequireseem to work as well, but there is an important difference between the two.

When calling thecontainFunction if the path of the file to be contained is invalid, a PHP warning (E_Warning) is shown, and the rest of the code will continue to be carried out.

On the other hand, when we call thatnecessaryFunction and an invalid file path are provided, a fatal PHP error is increased and your code ends there.

Let us see that this is in action through an example.

First, we will use themcontainFunction with a wrong file path.

<!Doctype html> <!-index.php-> <html long = "en"> <body> <?PHP Echo "Before the function is included, means <br>"; integrate 'abc.php'; // false file path provided <br> ✅ The remaining code will continue to be carried out. ";?> </body> </html>

EXIT:

How to use PHP instructions and need instructions | Scout APM blog (10)

As you can see, the code throws up a warning when we try to include an invalid file path, but then continue to carry out the lines.

note: Whether the warnings/error messages are displayed or not depends on your system. Since the error report in my system is activated, warning messages are displayed in my output. In most cases, howeverOutput that may not contain the warning or error message. In this case your edition could look like this - - -

How to use PHP instructions and need instructions | Scout APM blog (11)

You can manually configure the error report from your PHP code, as shown below -

error_reporting (0); // error in the deactivation of error reporting gerror_reporting (-1); // How to activate the error reporting

If you would like to learn more about error reporting in PHP, you can refer to our postHow to activate the reporting on PHP error reportingwhere we talk about it in detail.

Back to the use ofcontainAndrequireLet's take a look at how the tonecessaryThe function would behave if we enter an invalid file path.

We use the same example as above and replace themcontainFunction withrequire.

<!Doctype html> <!-index.php-> <html long = "en"> <body> <?PHP Echo "Before the function is included, means <br>"; require 'abc.php'; // invalid file path provided <br> ✅ The remaining code continues to be carried out. ";?> </body> <html>

EXIT:

How to use PHP instructions and need instructions | Scout APM blog (12)

As you can see, a fatal error message is charged and the code ends in the line with therequireInstruction - the remaining lines are not carried out.

This is the main difference between how tocontainand torequirework -containWorks a warning, but lets the rest of the code execute, althoughrequireThrows out a mistake and immediately violates your code.

Include VS requirement - which to use?

SincecontainIf the execution does not interrupt, it seems to be the better option. This can be the case for small personal projects in which the missions are not so high. For large -scale software systems, however, the contraguitive truth is that you want your application youmore drawn attention to potential inconsistency or inaccuracies in your code.

SomeInclude/desireCommands of their application that can be extremely critical for the normal functions.contain) In huge protocol files, manifest themselves into a much greater problem in the future if they are not taken into account. They would rather abrupt their code from time to time to abrupt a fatal error than to influence the functionality of their app when they are released for productionIt is important to take these errors and code exits into account, as they force them to make mistakes in their code aware and make it easier to make debugging.

(Video) Opening Keynote - ZendCon 2015

For example, consider incorrectly a wrong path for your database configuration file in the code.containYour invalid path warning could remain unnoticed and all of your database processes will be subject to production when your application goes into production. It will probably not know the reason for this problem because your code has gone well (it was not ended) andThe warnings may have to be overlooked. You have to spend some time to debug before you know what the problem was and where it happened.

ArequireThe statement would therefore be a better option in most such cases. The core idea is that errors, although they are bad for users, are very important for developers to consider inaccuracies in their code.

Prevent errors: PHP include_once and Request_once instructions

If you work on large projects, it is possible that you occasionally record the same PHP file in your code more than once.Contains.

Let's take a look at an example to understand this better.

Here is the external file with a function that we want to include -

<?php // my_file.php echo "<b> print from the file! </b> <br>"; function foo ($ boo) {echo foo foo function called! <br> "; $ boo += 5;Return $ boo;}?>

Now let's see what happens when we add this file to our main file several times.

<!Doctype html> <!-index.php-> <html long = "en"> <body> <?PHP Echo "Before the function is included, means <br>"; close 'my_file.php'; // Inclusion of the file once reproduced "File. Try to lock again! <br>"; close 'my_file.php 'a; // attempt to involve it again, reflect "it works.";?> </body> </hml>

Exit

How to use PHP instructions and need instructions | Scout APM blog (13)

As you can see, a fatal mistake has been addressed because the second time the file is included in order to reclaim an existing function that is not possible.

Even if the included file does not contain a function, including several files, sometimes sometimes quite inefficient.

To solve this problem, PHP offersinclude_onceAnduniqueFunctions that can take care of several file incorporations.

Let's try this with an example.

We will try to see the same file that we have seen in the previous exampleinclude_onceFunction.

<!Doctype html> <!-index.php-> <html long = "en"> <body> <?Php echo "before the function is included, means <br>"; include_once 'my_file.php'; // Inclusion of the file once included./Try to involve it again, reflect "✅ It worked.";?> </body> </hml>

EXIT:

How to use PHP instructions and need instructions | Scout APM blog (14)

As we can see, this time her file was not included the second time. We know that because the printer's declaration ofmy_file.phpWas only carried out once. The error was not increased and our code was not ended in the middle.

Theinclude_onceAnduniqueFunctions also give back a Boolean value, depending on whether the file was previously recorded or not.

The difference betweeninclude_onceAnduniqueis the same difference betweencontainAndrequire.It means thatinclude_onceonly emits one warning to an invalid file path whileuniqueIf an error increases and stops the code version.

Conceptions

In this article we first talked about the importance of writing modularized and reusable code. We learned about thatcontainAndrequireFunctions in PHP - as you enable us to import other PHP files into our code. We have seen how these functions differ significantly despite the similarity in the way they behave, when an invalid file path argument is providedwe discussed the difference between the two and talked about itrequireCould be a better option than compared tocontainWe also looked at thatinclude_onceAnduniqueFunctions - about how you can check for several file incoming and you can only insert a file once. During the entire contribution, we have also looked at a number of examples to consolidate our understanding of how these functions can be practically implemented.

Now that you know how to record files in your PHP code, try to implement this in a personal project.have done the above examples. You can then create a number of different websites that contain (or require) these children's components. You can also create a utility class file with some functions that can be used by the pages of your website.

Stay healthy, stay safe and learn! Happy coding!

(Video) ElasticSearch PHP Client

Have you found this article helpful or saw something you do not agree with or think that it should be improved? Please let us know, we appreciate your feedback!

Videos

1. InsertCoin 16.1.2 - SENSE 5 Addons - APM - EQS - OPTIMIZED - 3.18.401.1
(Flo WolfOne)
2. PHP - Monitoring a PHP application with OpenTelemetry and SigNoz
(SigNoz - Open Source Observability Platform)
3. PHP Release Radar - Episode 4: XDebug 3
(PHP Release Radar)
4. Session-1 - NewRelic Advance Tutorials - Introduction & APM
(TheDevOpsSchool)
5. Elastic Load Balancer Tutorial | AWS | AWS ELB Tutorial for beginners | Complete Video From Scratch
(NetMinion Solutions)
6. Ruby Programming Language for Beginners - Crash Course 2020
(David Battersby)
Top Articles
Latest Posts
Article information

Author: Dong Thiel

Last Updated: 08/06/2023

Views: 6111

Rating: 4.9 / 5 (59 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Dong Thiel

Birthday: 2001-07-14

Address: 2865 Kasha Unions, West Corrinne, AK 05708-1071

Phone: +3512198379449

Job: Design Planner

Hobby: Graffiti, Foreign language learning, Gambling, Metalworking, Rowing, Sculling, Sewing

Introduction: My name is Dong Thiel, I am a brainy, happy, tasty, lively, splendid, talented, cooperative person who loves writing and wants to share my knowledge and understanding with you.