使用函数初始化变量(如果未设置)-PHP [英] Using a function to initialise a variable if it not set - PHP

查看:53
本文介绍了使用函数初始化变量(如果未设置)-PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在执行脚本时,有时会设置变量,有时则不会.并非如此,我已经注意到未定义变量.

Upon executing a script, sometimes the variable will be set, and sometimes it won't. The times that it isn't, I'm given a notice that the variable is not defined.

为了清除通知,我简单地添加了以下代码

In efforts to clear the notice, I simple added the following code

if(!isset($var)) {
    $var = NULL;
}

这可以按需工作,因为它会测试变量是否尚未设置,以便我们不必设置 NULL 所需的内容.但是,在一个文件中,有60多个这种情况的变量,并且以后还会有更多变量,我认为创建一个简单的函数来完成此操作会更容易.所以我从这里开始:

That works just as needed because it tests if the variable isn't already set so that we don't set something that we need to NULL. But in a file where there are over 60 variables that are of this case and more to come, I thought creating a simple function to do so would be easier. So I started with this:

function init($var) {
    if(!isset($var)) {
        return $var = NULL;
    }
}

显然这是行不通的,而且还充斥着错误,这些错误会使大多数程序员烦恼(例如函数内的!isset(),如果if语句为假,等等),但这只是为您提供了我所需要的基本知识,因此在代码中,我可以调用 init($ var); 来测试变量是否尚未设置,然后创建一个并将其设置为 NULL 以避免发出通知.

Obviously that doesn't work and is also riddled with errors that will annoy most programmers out there (such as the !isset() inside a function, not supplying a return statement in case the if statement is false, etc.) but that's just to give you the basic jist of what I need so in the code I can just call init($var); to test if the variable isn't already set, and then creates one and sets it to NULL to avoid the notice.

这甚至有可能吗?要使用函数来测试变量是否已在函数外部设置?在此先感谢:)

Is this even possible? To use a function to test if a variable is already set outside of the function? Thanks in advance :)

推荐答案

在将变量作为参数传递给函数的过程中,如果不对其进行初始化,就无法使用函数来检查变量是否存在.但是,您可以定义脚本需要的变量名称数组,然后遍历它们并检查它们是否一个一个地存在.如:

You can't use a function to check if a variable exists without it being initialized in the process of passing it to the function as an argument. You can, however, define an array of variable names your script requires then loop through them and check if they exist one by one. Such as:

foreach(array('username','userid','userrole','posts','dob','friends') as $var)
{
    if(!isset($$var))$$var=NULL;
}

简化user4035的方法,您可以将功能简化为:

Simplifying user4035's approach, you could get the function down to:

<?php
function init(&$var){}
init($myVariable);
var_dump($myVariable);

甚至完全避免使用函数:

Or even avoid a function altogether:

<?php
array(&$var1,&$var2,&$var3);//define several variables in one shot as NULL if not already defined.
var_dump($var1);
var_dump($var2);
var_dump($var3);

另一种方法是使用提取:

<?php
$defaults=array('username'=>NULL,'userid'=>0,'userrole'=>'guest','posts'=>0,'dob'=>0,'friends'=>array());

$userid=24334;
$username='bob';
$friends=array(2,5,7);

extract($defaults, EXTR_SKIP);
echo '<pre>';
print_r(
    array(
    'userid'=>$userid,
    'username'=>$username,
    'friends'=>$friends,
    'userrole'=>$userrole,
    'posts'=>$posts,
    'dob'=>$dob)
);
echo '</pre>';

另一种方法是暂时禁用错误报告:

Another approach would be to temporarily disable error reporting:

<?php
$v=ini_get("error_reporting");
error_reporting(0);
echo 'One';
echo $doh;//Use an undefined variable
echo ' Two';
error_reporting($v);

我建议您不要使用这种方法,因为它只是隐藏错误而不是修复错误,并且还会隐藏值得您注意的错误.

I'd advise against this approach though because it is just hiding the errors rather than fixing them and will also hide errors worthy of your attention.

我个人最喜欢的是利用命名空间.
通常,您会将它们放在单独的文件中,但为了方便起见,我将它们放在单个代码段中:

And my personal favorite would be to take advantage of namespaces.
Usually you'd put these into separate files but I put them into a single snippet for your convenience:

<?php
namespace //This is the global namespace
{
    $config=array('production'=>0);
}

namespace MyScript
{
   //Initialize all variables for our script
   //anything not defined here will be inherited from the global namespace
    $username=NULL;
    $userid=NULL;
    $userrole=NULL;
    $posts=NULL;
    $dob=NULL;
    $friends=NULL;

}

namespace MyScript\Main
{
//Define only two variables for our script
//Everything else will be inherited from the parent namespace if not defined
$username='Ultimater';
$userid=4;

    echo '<pre>';
    print_r(
        array(
        'userid'=>$userid,
        'username'=>$username,
        'friends'=>$friends,
        'userrole'=>$userrole,
        'posts'=>$posts,
        'dob'=>$dob,
        'config'=>$config)
    );
    echo '</pre>';
}

这篇关于使用函数初始化变量(如果未设置)-PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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