【问题标题】:Object Oriented PHP return database row and access array elements面向对象的 PHP 返回数据库行并访问数组元素
【发布时间】:2012-05-15 12:57:28
【问题描述】:

我是面向对象 PHP 概念的新手(遵循 www.killerphp.com 上的教程),我计划将我所有的 php 应用程序迁移到 OO PHP。
我开始构建我的第一个类,它根据 "setSecurity()" 方法设置的 "where" 条件中的对象属性从数据库中读取授权级别。

我设法返回了数组 "getSecurity()" 但打印输出会给出:

security Object
(
    [secArray] => Array
        (
            [from_date1] => 1992-01-01
            [to_date1] => 0000-00-00
            [from_date2] => 1992-01-01
            [to_date2] => 0000-00-00
            [view] => 1
            [insert] => 0
            [update] => 1
            [delete] => 1
            [valid] => 1
        )

)
/*"Array 1"*/

我的问题是我不熟悉普通数组的打印输出(如下)。

Array
(
    [from_date1] => 1992-01-01
    [to_date1] => 0000-00-00
    [from_date2] => 1992-01-01
    [to_date2] => 0000-00-00
    [view] => 1
    [insert] => 0
    [update] => 1
    [delete] => 1
    [valid] => 1
)
/*"Array 2"*/

我的问题是: 1) 如何从 getSecurity() 方法(从数组 1)访问数组的元素?
2) 如何让我的方法正确返回数组(与数组 2 相同)?

以下代码片段。

非常感谢您的支持...

'test.php'

<?php
include("connect.php");  
include("security.php");
$secArray=new security();
$secArray->setSecurity('test_user',1,1,1,$link);
$secArray->getSecurity();
echo "<pre>"; print_r($secArray); echo "</pre>";
?>

'security.php'

<?php
class security
{
    public $secArray = array();

    function setSecurity($user,$appid,$funid,$objid,$conn='')
    {
        $query="SELECT lu.DATE1 as from_date1,
                    lu.DATE2 as to_date1,
                    ga.DATE1 as from_date2,
                    ga.DATE2 as to_date2,
                    ga.VIEW as view,
                    ga.INSERT as insert,
                    ga.UPDATE as update,
                    ga.DELETE as delete,
                    ob.VALID as valid
                FROM
                    user as lu
                    inner join group as ug on lu.GRP_ID = ug.ID
                    inner join privileges as ga on lu.GRP_ID = ga.GRP_ID
                    and ug.ID = ga.GRP_ID
                    inner join level1 as ob on ob.APP_ID = ga.APP_ID
                    and ob.FUN_ID = ga.FUN_ID
                    and ob.ID = ga.OBJ_ID
                where
                    USERID = '$user'
                and ga.APP_ID = $appid
                and ga.FUN_ID = $funid
                and ga.OBJ_ID = $objid";
        $result = mysql_query($query,$conn);
        $row = mysql_fetch_assoc($result);
        $this->secArray=$row;
    }

    function getSecurity()
    {
        return $this->secArray;
    }     
}
?>

【问题讨论】:

  • $secArray-&gt;secArray['from_date1'] 等等。

标签: php mysql arrays oop return


【解决方案1】:

getter 返回一个值,因此调用$secArray-&gt;getSecurity(); 并不能真正帮助您,除非您对返回的值执行某些操作。 $mySecurity=$secArray-&gt;getSecurity();use $mySecurity...

请阅读有关访问数组和对象的 PHP 文档。

【讨论】:

  • 感谢 Marc 和 RADU 的大力协助
猜你喜欢
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 2014-06-10
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 2016-02-02
  • 2013-02-19
相关资源
最近更新 更多