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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog