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

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: Fol…


This content originally appeared on DEV Community and was authored by Eric The Coder

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>';
}

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>

In this example, we discover the require() function. 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 function

Allows you to do exactly the same thing as the require() function 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 functions 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!");

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!");

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!");

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!");

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);

Read a file

$content = file_get_contents("test.txt");

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
}

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);

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');

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);

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;
}

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

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);

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

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_


This content originally appeared on DEV Community and was authored by Eric The Coder


Print Share Comment Cite Upload Translate Updates
APA

Eric The Coder | Sciencx (2022-01-28T15:07:05+00:00) PHP crash course : require, include, files manipulation and enuerations. Retrieved from https://www.scien.cx/2022/01/28/php-crash-course-require-include-files-manipulation-and-enuerations/

MLA
" » PHP crash course : require, include, files manipulation and enuerations." Eric The Coder | Sciencx - Friday January 28, 2022, https://www.scien.cx/2022/01/28/php-crash-course-require-include-files-manipulation-and-enuerations/
HARVARD
Eric The Coder | Sciencx Friday January 28, 2022 » PHP crash course : require, include, files manipulation and enuerations., viewed ,<https://www.scien.cx/2022/01/28/php-crash-course-require-include-files-manipulation-and-enuerations/>
VANCOUVER
Eric The Coder | Sciencx - » PHP crash course : require, include, files manipulation and enuerations. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/01/28/php-crash-course-require-include-files-manipulation-and-enuerations/
CHICAGO
" » PHP crash course : require, include, files manipulation and enuerations." Eric The Coder | Sciencx - Accessed . https://www.scien.cx/2022/01/28/php-crash-course-require-include-files-manipulation-and-enuerations/
IEEE
" » PHP crash course : require, include, files manipulation and enuerations." Eric The Coder | Sciencx [Online]. Available: https://www.scien.cx/2022/01/28/php-crash-course-require-include-files-manipulation-and-enuerations/. [Accessed: ]
rf:citation
» PHP crash course : require, include, files manipulation and enuerations | Eric The Coder | Sciencx | https://www.scien.cx/2022/01/28/php-crash-course-require-include-files-manipulation-and-enuerations/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.