PHP参数的用途 [英] Purpose of PHP parameters

查看:95
本文介绍了PHP参数的用途的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解PHP函数的概念。我知道如何创建一个。

 函数functionName()
{
//要执行的代码;
}

我也知道如何调用一个函数。对于参数的用途我有点困惑。我已经阅读了PHP手册和w3schools.com的教程。根据我的理解,你需要一个参数来传递一个值给函数?如果这是正确的,为什么不在功能中创建它?为什么使用参数?



像这样:

 <?php 
函数num()
{
$ s = 14;
echo $ s;
}
num();
?>

我知道您可以这样做:

<?php 
函数num($ s = 14)
{
echo $ s;
}
num();
?>

或:

 <?php 
函数num($ s)
{
echo $ s;
}
num($ s = 14);
?>

有人可以给我一个真正的使用参数的应用程序,比如说一个基于用户的动态内容网站?我认为这会帮助我更好地理解它。

解决方案

传递一个参数可以让你多次使用一个函数。例如:

如果您想编写一个发送邮件的函数 - 您可以传递以下参数:

  $ to = $ _POST ['to']; 
$ from = $ _POST ['from'];
$ subject = $ _POST ['subject'];

然后,在您的函数中:

<$ p

















$ / code>

现在您可以在您的网络应用程序的各个位置重复使用您的发送功能。


I am trying to grasp the concept of PHP functions. I know how to create one.

function functionName()
{
    //code to be executed;
}

I also know how to call a function. I am just a little confused as to what a parameter is for. I have read the php manual and w3schools.com's tutorial. From my understanding, you need a parameter to pass a value to the function? If that is correct why not just create it within the function? Why use a parameter?

Like this:

<?php
function num()
{
$s=14;
echo $s;
}
num();
 ?>  

I know you can do:

<?php
function num($s=14)
{
    echo $s;
}
num();
?>

or:

<?php
function num($s)
{
    echo $s;
}
num($s=14);
?>

Could someone give me a real application of using a parameter, for say maybe a user based dynamic content website? I think it would help me understand it better.

解决方案

Passing a parameter allows you to use one function numerous times. For example:

If you wanted to write ONE function that sent mail - you could pass the following parameters:

$to = $_POST['to'];
$from = $_POST['from'];
$subject = $_POST['subject'];

Then, in your function:

 function sendmail($to, $from, $subject){

//code to be executed

}

Now you can reuse your send function at various points in your web app.

这篇关于PHP参数的用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆