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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?