PHP类 - 调用数组变量

时间:2013-09-21 21:38:41

标签: php class variables

我被困在这段代码的一部分..我试着调用我的静态表变量,但我不能。

Methinks我有一个非常简单的问题,但对我的项目有效且有害。

我的班级:

<?php

public $table;

class Functions
{
    public function ehe()
    {
        return $table[4];
    }
}

?>

我的system.php文件:

    $fn = new Functions();

    /* static tables */
    $table  = array(
                    0 => 'account.account',
                    1 => 'player.player',
                    2 => 'auction_house.items',
                    3 => 'auction_house.admin',
                    4 => 'auction_house.store',
                    5 => 'auction_house.styles',
                    6 => 'auction_house.logs',
                    7 => 'auction_house.coupons',
                    );

我的索引文件(示例):(与system.php&amp; classes连接)

echo $fn->ehe;

我的错误:

Notice: Undefined property: Functions::$ehe in C:\Program Files (x86)\EasyPHP-DevServer-13.1VC9\.......php on line 178

一个小问题: 我也有2节课。 1:函数类。 (包括查询处理等) 2:MySQL连接类。 我想连接这两个类进行查询。这怎么可能? ..

2 个答案:

答案 0 :(得分:1)

你需要调用它,它是一个函数,而不是一个属性。

echo $fn->ehe();

答案 1 :(得分:0)

您的代码存在一些问题:

  • 您正在访问ehe,就好像它是属性而不是方法。方法调用始终具有(),如果需要,它们包含参数。
  • 您无法修改全局范围内变量的可见性 - 您的public $table;会导致语法错误。
  • $table超出了ehe()方法的范围。

您可以使用global关键字:

$table;

class Functions {
    public function ehe() {
        global $table;
        return $table[4];
    }
}

$fn = new Functions();

/* static tables */
$table = array(
            0 => 'account.account',
            1 => 'player.player',
            2 => 'auction_house.items',
            3 => 'auction_house.admin',
            4 => 'auction_house.store',
            5 => 'auction_house.styles',
            6 => 'auction_house.logs',
            7 => 'auction_house.coupons',
        );

echo $fn->ehe(); // auction_house.store