There are many concepts in PHP that create confusion for beginners. Some of the main ones are as follows:
The first two words display strings, and the last two call a file inside another one.
Let’s get started.
// echo echo 'This is a string'; // print print 'This is a string';
echo, we can have more than one parameter. The
1. The return value for
<?php echo "<h1>Educative, Inc</h1>"; echo "<p>This is Educative. The best place to learn!</p>"; echo '"echo"', " with multiple ", "parameters\n"; $name = "Patience Kavira"; print "Your name is $name"; // Non-string values are coerced to string print 5 * 5;
We can learn more about
We use both
require to call a PHP script inside another one. Imagine we build a website that has a common code like
footer. What do we do to work with these code snippets on different pages of our site?
If we want to write clean code and follow the DRY principle, we'll need to put common code in a single file and call it where needed.
Let's see another example. In most cases, config or sensitive information, like the database, is kept in a separate file. Therefore, we'll need to call this file every time we want to access the database.
Let's look at the syntax and the difference between them:
require "path/to/file"; // or include "path/to/file";
The only difference between
include is when the called file is missing. In such cases,
require produces a fatal error and stops the script while
include continues running but produces a warning. Hence, as a general rule, it is preferable to use
require for sensitive files and
include for others.
<?php /** * @author Abel L Mbula */ include "includes/header.php"; echo "<h1>Contact</h1>"; echo "<p>firstname.lastname@example.org</p>"; include "/includes/footer.php";
We've learned that
echo can accept multiple parameters. On the other hand, we also learned that to call a file inside another file, we use
require. The difference between them is that
include does not throw a fatal error when the called file is missing, while
View all Courses