Functions in PHP... How to use?

Asked

Viewed 98 times

0

For a website a php file was created that contains the functions for calculating a person’s Body Mass Index (BMI) in the funcoes.php file.

You want to use this function on the main page (index.php). What code is needed to insert the funcoes.php file into the index.php file?

(Include, import, use, add or echo ?)

2 answers

1


To import/merge code in PHP, there are functions:

  1. require 'caminho/para/seu/arguivo.php'
  2. require_once 'caminho/para/seu/arquivo.php'
  3. include 'caminho/para/seu/arquivo.php'
  4. include_once 'caminho/para/seu/arquivo.php'

All these functions serve to import code. The only difference between "include" and "require" is that they treat possible errors differently.


In a scenario where the file you want to import does not exist, for example:

In the include function, the code will continue running, but an error alert will be displayed on your site.

In the require function, a fatal error (fatal error) will be generated and code execution will stop.


The two variants of the functions, "require_once" and "include_once", mean that PHP will check whether the file has already been included previously, and if so, it will not be included again.

Example:

<?php  

require 'meuarquivo.php' // Inclui o arquivo
require_once 'meuarquivo.php' // Não inclui o arquivo de novo, pois ele já fui incluído acima. 

?> 

0

Debris from the code of index.php you must include the file that contains the function using include or require.

include 'nome_do_arquivo.php';

or

require 'nome_do_arquivo.php';

Done that, just call the function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.