2011-08-14 36 views
1

您好我只是想知道是否有更好的办法做这样的事情:一个更好的方法,如果一个变量isset PHP

$openid = $_SESSION['openiduserdata']; 
if (isset($openid['namePerson/friendly'])) 
    {$username = $openid['namePerson/friendly'];} 
if (isset($openid['namePerson/first'])) 
    {$firstname = $openid['namePerson/first'];} 
if (isset($openid['namePerson/last'])) 
    {$lastname = $openid['namePerson/last'];} 
if (isset($openid['birthDate'])) 
    {$birth = $openid['birthDate'];} 
if (isset($openid['contact/postalCode/home'])) 
    {$postcode = $openid['contact/postalCode/home'];} 
if (isset($openid['contact/country/home'])) 
    {$country = $openid['contact/country/home'];} 
if (isset($openid['contact/email'])) 
    {$email = $openid['contact/email'];} 
+0

现在还不清楚要如何处理在您的示例代码默认(看起来像您以后需要再次探讨每个变量的存在)。但是你可能想使用一个数组映射而不是单个的'if'语句。 – mario

+0

我有一个问题:为什么你需要把三次相同的值放在内存中? $ _SESSION ['openiduserdata'],$ openid和$ username等等。 – corretge

回答

2

如果你的目标是避免PHP通知,只是前缀数组与@变量:

$username = @$openid['namePerson/friendly']; 
+3

哇,真的吗?这是一种可怕的做法,可能会导致漫长的夜晚“白页调试”。 – AlienWebguy

+1

@AlienWebguy:实际上恰恰相反。 OP的原始代码片段将永远不会发出单一的可追踪音符。但是,@ -suppressed通知仍然可以在需要时重新显示(作为日志,使用自定义错误处理程序)。在这种情况下,根本不重要***。 – mario

+0

我完全不同意马里奥。你认为OP每次不工作时都会记得寻找'@'。这是一个不好的习惯,抑制通知/警告,而不是正确的错误检查和失败。 – AlienWebguy

5
$variables = array('openid' => 'openiduserdata', 'username' => 'namePerson/friendly', 'firstname' => 'namePerson/first', 'lastname' => 'namePerson/last', 'birth' => 'birthDate', 'postcode' => 'contact/postalCode/home', 'country' => 'contact/country/home', 'email' => 'contact/email'); 

foreach ($variables as $name => $key) 
    if (isset($openid[$key])) 
    $$name = $openid[$key]; 
+0

变量变量......我不能让自己使用任何解决方案,即使它可能是最好的想法。 –

+0

我并不责怪你的直觉,但在这种情况下,变量名称来自硬编码数组,而不是用户输入或任何类似的危险。程序员已经定义了相同的变量名称。 –

+0

是的,我知道...但仍...呃。 –

1

如果你试图设置只有那些不是数组为默认值设置选项,一个解决方案是创建一个包含所有默认值的数组,然后合并th e传入数组与默认数组。

<?php  
$defaults = array('name' => 'Anonymous','gender' => 'n/a'); 
$data = array_merge($defaults, $_POST); 
// now data includes all the post parameters, however, those parameters that don't exist will be the default value in $data 
+0

+1。在发布我的想法之前,我误解了你的答案。 – Paul

0

尝试就这样创造功能:

function get_value_or_default($array, $key, $default = null) 
{ 
    if (array_key_exists($key, $array)) 
    { 
     return $array[$key]; 
    } 
    else 
    { 
     return $default; 
    } 
} 

$username = get_value_or_default($openid, 'namePerson/friendly'); 
0
$openid = array_merge(
    array('namePerson/friendly' => NULL, // Or an empty string if you prefer. 
     'namePerson/first' => NULL, 
     'namePerson/last'  => NULL), // etc. 
    $_SESSION['openiduserdata']); 

// Now you know that the keys are set. 
// Then if you really need them separate: 
$username = openid['namePerson/friendly']; 
$firstname = openid['namePerson/first']; 
$lastname = openid['namePerson/last']; 
// etc. 
相关问题