Home > headlines > Declaration and use of php functions

Declaration and use of php functions

无忌哥哥
Release: 2018-06-28 10:02:50
Original
2612 people have browsed it

* Function

* 1. Declaration syntax;

* 2. Calling method;

* 3. Parameter setting;

* 4. Return value;

* 5. Scope

//Declaration

function hello() //无论有无参数,圆括号不能省略
{
    echo '欢迎来到php中文网学习';
}
Copy after login

//Call: call by name, must bring parentheses

hello();
echo &#39;<hr>&#39;;
//可以设置参数
function hello1($siteName)
{
    echo &#39;欢迎来到&#39;.$siteName.&#39;学习&#39;;
}
Copy after login

//You must bring parameters when calling now

hello1(&#39;php中文网&#39;);
hello1(&#39;www.php.cn&#39;);
Copy after login

//If you forget to give parameters when calling, you can give the function parameters a default value

function hello2($siteName = &#39;php中文网&#39;)
{
    echo &#39;欢迎来到&#39;.$siteName.&#39;学习&#39;;
}
echo &#39;<hr>&#39;;
Copy after login

//You can pass parameters when calling now , you can also pass no parameters

hello2();
echo &#39;<br>&#39;;
hello2(&#39;PHP中文网_www.php.cn&#39;);
Copy after login

//If there are multiple parameters, the default value should be written to the end

function hello3($name ,$siteName = &#39;php中文网&#39;)
{
    echo &#39;我是&#39;.$name.&#39;,欢迎来到&#39;.$siteName.&#39;学习&#39;;
}
echo &#39;<hr>&#39;;
Copy after login

//Calling method

hello3(&#39;peter zhu&#39;); //第一个参数没有默认值,必须传参
echo &#39;<br>&#39;;
hello3(&#39;peter zhu&#39;, &#39;www.php.cn&#39;); //实参与形参的位置必须一一对应
echo &#39;<hr>&#39;;
Copy after login

//Scope : Function internal variables cannot be accessed from the outside. Similarly, external variables cannot be accessed from inside the function.

$siteName = &#39;php中文网&#39;;
Copy after login

//External variables, or global variables, will automatically become an element in the global variable array $GLOBALS. The variable is The key name of the element

echo $GLOBALS[&#39;siteName&#39;]; //它里面的数据就是变量siteName中的值,而且这是一个超全局变量,可以在函数中使用
function hello4()
{
    $name = &#39;peter zhu&#39;;
//    return $siteName;
    return $GLOBALS[&#39;siteName&#39;];
}
echo hello4();
echo &#39;<br>&#39;;
echo $name; //外部是访问不到函数内的变量的,除非函数将这个变量返回到外部
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template