duanquannan0593 2013-07-02 15:16
浏览 44
已采纳

在数组中使用变量

Can someone help me how to change value of an array to variable?

I would like to change from this:

class SimpleAuth
{
var $users = array(
    'admin1' => 'password1',  //
    'admin2' => 'password2',  // User 2
    'admin3' => 'password3',  // User 3
    'admin4' => 'password4',  // User 4
);
}

to:

$user = 'admin'; // value from an include file outside the class declaration
$password = 'password'; // value from an include file outside the class declaration

class SimpleAuth
{
var $users = array(
    $user => $password,       // User 1 // here is the error
    'admin2' => 'password2',  // User 2
    'admin3' => 'password3',  // User 3
    'admin4' => 'password4',  // User 4
);
}

I get 500 error. Please help! Thanks

  • 写回答

3条回答 默认 最新

  • duanlu1908 2013-07-02 15:20
    关注

    are you looking for something like this without var. var was used to declare class member variables prior to php 5. it is still supported for backward compatibility but it only has meaning inside a class context.

    $users = array(
    $user => $password,       // User 1 // here is the error
    'admin2' => 'password2',  // User 2
    'admin3' => 'password3',  // User 3
    'admin4' => 'password4',  // User 4
    

    );

    UPDATE, you can't use dynamic values when your defining the class members, as the variables will have no values when the class gets initiated. move your assignment to the __construct. In your case the construct is same as your class name.

    function className() {
             $user = 'admin';
    $password = 'password';
    
         $this->users[$user] = $password;
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码