DEV Community

Cover image for PHP crash course : require, include, files manipulation and enumerations
Eric The Coder
Eric The Coder

Posted on • Updated on

PHP crash course : require, include, files manipulation and enumerations

Today you will learn conditionals, loops and functions création in PHP.

This PHP crash course is free and will be posted here on dev.to. I'll be releasing a new article/post every two days or so. To not miss anything, you can follow me on twitter: Follow @EricTheCoder_

require and include

So far we have created only one PHP file for all our tests.

When creating an application it will almost always be otherwise. Very quickly we will need to split/organize our code into multiple files.

Here we will see two instructions that allow you to execute code that has been defined in another file.

To do this we will create two files. The first named message.php and write the following code

<?php

function sendMessage(string $message)
{
    echo $message . '<br>';
}
Enter fullscreen mode Exit fullscreen mode

Here it is simple code from simple. A small function that displays a message and a line break.

Then, create the second file named index.php and write the following code

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <?php
        require 'message.php';
        sendMessage('Hello World');
    ?>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

In this example, we discover the require instruction. It allows to include the code of the message.php file. So therefore allows the use of the function sendMessage()

What happens if the file specified as a parameter does not exist? In this case, PHP will return an error.

The include instruction

Allows you to do exactly the same thing as the require instruction except that PHP will not return an error (only a Warning) if the file to include is not present.

require_once et include_once

These instructions are identical to their sister function (require and include). The difference is that PHP will include the file only if it hasn't already.

Manipulation of files and folders

PHP includes several functions to manipulate folders and files on the server

Here are some very useful functions

Create file

file_put_contents("test.txt", "Hello World!");
Enter fullscreen mode Exit fullscreen mode

This function will create the test.txt file (in the current folder) with the content 'Hello World'.

It is possible to specify the folder.

file_put_contents("data/test.txt", "Hello World!");
Enter fullscreen mode Exit fullscreen mode

If the folder does not exist, PHP will return a warning

You can create the folder with mkdir function

mkdir('data');

file_put_contents("data/test.txt", "Hello World!");
Enter fullscreen mode Exit fullscreen mode

Note that to delete a folder you can use the rmdir() function. The folder must be empty for its deletion to be possible.

If you want to create the file in a folder that is parent to the current folder use the colon . .

file_put_contents("../test.txt", "Hello World!");
Enter fullscreen mode Exit fullscreen mode

The file will be created in the parent folder

If the file already exists, the file_put_contents function will replace the existing file. If your goal is to append to the existing file, use the FILE_APPEND option

file_put_contents("test.txt", "Hello World!", FILE_APPEND);
Enter fullscreen mode Exit fullscreen mode

Read a file

$content = file_get_contents("test.txt");
Enter fullscreen mode Exit fullscreen mode

If the file does not exist, PHP will return a warning

To check if the file exists you can use the file_exists() function

if (file_exists('/posts/first.txt')) {
  // do some stuff
}
Enter fullscreen mode Exit fullscreen mode

Read a file line by line

The previous function allowed to read a file at once. There is a function to read line by line.

$file = fopen("test.txt", "r");

while(! feof($file)) {
  $line = fgets($file);
  echo $line. "<br>";
}
fclose($file);
Enter fullscreen mode Exit fullscreen mode

here the file is opened with the 'r' option for read.

The code block will run until the end of file is detected feof()

Write to file line by line

$file = fopen('export.csv', 'w');
Enter fullscreen mode Exit fullscreen mode

Here the file is opened with the 'w' option to create or overwrite. If we wanted to make an addition we could have used the option 'a' to add

Once the file is open, you can insert lines

$array = [
    ['name' => 'Mike', 'age' => 45],
    ['name' => 'John', 'age' => 38],
]

//Write key name as csv header
fputcsv($file, array_keys($array[0]));

//Write lines (format as csv)
foreach ($array as $row) {
    fputcsv($file, $row); 
}
fclose($file);
Enter fullscreen mode Exit fullscreen mode

The fputfile() function allows to write lines. Here we have rather used its sister function fputcsv() which does essentially the same thing but in csv format.

Note that we used an fputcsv before the loop. This line will be the first line of the file and should include the column names. The array_keys() function allows you to retrieve the name of the array keys (name and age)

Enumerations

Enumerations, or "Enums" make it possible to define a personalized “type” which will be limited to one of the possible values among those specified. Enums are a type of object and therefore can be used anywhere an object can be used.

Here is an example statement

// Définir le nom et les valeurs posssible
enum InvoiceStatus
{
    case Sent;
    case Paid;
    case Cancelled;
}
Enter fullscreen mode Exit fullscreen mode

This declaration creates an InvoiceStatus type which can have only three values

InvoiceStatus::Sent

InvoiceStatus::Paid

InvoiceStatus::Cancel

It is possible to use this type in a function with type hint

function printInvoiceStatus(InvoiceStatus $status)
{
    print($status->name);
}

printInvoiceStatus(InvoiceStatus::Sent);
// Sent
Enter fullscreen mode Exit fullscreen mode

The name property is used to retrieve the name of the case

It is possible to associate a value for each of the “case”. To do this, it is absolutely necessary to specify the type of the enum when declaring it: ex. enum InvoiceStatus : int

It is also possible to add a method to our enum

enum InvoiceStatus : int
{
    case Sent = 0;
    case Paid = 1;
    case Cancelled = 2;
}

print(InvoiceStatus::Paid->value);
Enter fullscreen mode Exit fullscreen mode

The value property allows you to retrieve the value associated with the “case”

Just like an object, it is possible to add a method to the Enum

enum InvoiceStatus : int
{
    case Sent = 0;
    case Paid = 1;
    case Cancelled = 2;

    public function text() : string
    {
        return match ($this) {
            self::Sent => 'Sent',
            self::Paid => 'Paid',
            self::Cancelled => 'Cancelled'
        };
    }
}

function getInvoiceStatus(InvoiceStatus $status)
{
    print($status->text());
    print($status->value);
}

getInvoiceStatus(InvoiceStatus::Paid);
// Paid1
Enter fullscreen mode Exit fullscreen mode

The method can access the “case” of the enum via the keyword self::

Finally, each value can call the ex function. InvoiceStatus→text()

Conclusion

That's it for today, I'll be releasing a new article every two days or so. To be sure not to miss anything you can follow me on twitter: Follow @EricTheCoder_

Latest comments (2)

Collapse
 
reubenwalker64 profile image
Reuben Walker, Jr.

You have a typo in your title. Enumerations. I am enjoying the series. Keep up the good work. Au revoir.

Collapse
 
ericchapman profile image
Eric The Coder

Thanks for your comment. I corrected the title.