Home  >  Article  >  Declaration and use of php functions

Declaration and use of php functions

无忌哥哥
无忌哥哥Original
2018-06-28 10:02:502557browse

* Function

* 1. Declaration syntax;

* 2. Calling method;

* 3. Parameter setting;

* 4. Return value;

* 5. Scope

//Declaration

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

//Call: call by name, must bring parentheses

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

//You must bring parameters when calling now

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

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

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

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

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

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

$siteName = &#39;php中文网&#39;;

//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; //外部是访问不到函数内的变量的,除非函数将这个变量返回到外部
Statement:
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
Previous article:php loop structureNext article:php loop structure