php - 如何修复此非法偏移类型

时间:2013-10-19 11:07:51

标签: php

我收到一条错误消息,说我在此代码中有非法的偏移量:

function _generate_users($ceny, $komu, $ile, $admin=false){
    $price=($ceny*$ile);
    if($admin == false){
        $this->ceny['rent'] = $ceny['rent'];
        $this->ceny['pay'] = $ceny['pay'];
        $this->ceny['rec'] = $ceny['rec'];
    }
}//Function ends.

非法偏移分为以下三行:

$this->ceny['rent'] = $ceny['rent'];
$this->ceny['pay'] = $ceny['pay'];
$this->ceny['rec'] = $ceny['rec'];

2 个答案:

答案 0 :(得分:1)

在引用密钥之前,您需要检查密钥是否存在:

if ($admin == false) {
    foreach (array('rent', 'pay', 'rec') as $key) {
        if (array_key_exists($key, $ceny)) {
            $this->ceny[$key] = $ceny[$key];
        }
    }
}

但是,您上面也使用$ceny作为数字类型; $ceny的类型是什么?我建议添加is_array支票,但看起来您需要考虑如何使用变量。

答案 1 :(得分:0)

试试这个,你需要在尝试访问它之前检查你的偏移是否已经设置

private $ceny = array();

function _generate_users($ceny, $komu, $ile, $admin=false){
    $price=($ceny*$ile);
    if($admin == false){
        $this->ceny['rent'] = (isset($ceny['rent'])) ? $ceny['rent'] : '';
        $this->ceny['pay'] = (isset($ceny['pay'])) ? $ceny['pay'] : '';
        $this->ceny['rec'] = (isset($ceny['rec'])) ? $ceny['rec'] : '';
    }
}