为什么这个数组在我的PHP类中不被识别为数组?

时间:2017-01-18 01:32:49

标签: php

我正在尝试使用PHP中的面向对象编程来使我的PHP代码更多可重用和更加模块化。

它终于点击了,我得到它并看到在我的代码中使用类的好处,但在测试中遇到了一个我无法理解的问题。

我有两个用户阵列'名称

$commDocsAdminUsers
$commDocsAdminExecutiveUsers

我有以下类来创建一个新的$ currentUser,并且我正在尝试使用in_array来查找找到该用户的那两个数组中的哪一个。

我不断收到PHP错误,说它不认为数组是数组:

Warning: in_array() expects parameter 2 to be array, null given in - on line 25

这是我正在使用的......

<?php
    //ARRAYS OF USERS TO CHECK AGAINST
    $commDocsAdminUsers = array("kaisersolze", "bennyblanco", "carlitobrigante", "ashylarry", "claytonbigsby");
    $commDocsAdminExecutiveUsers = array("waltjr", "skylerwhite", "tuco", "skinnypete", "walterwhite");



class userLogin {


    // ALLOWS US TO SET THE NAME OF USER
    function set_name($new_name) { 
        $this->name = $new_name;  
    }

    // ALLOWS US TO GET THE NAME OF USER
    function get_name() {
        return $this->name;
    }

    // ALLOWS US TO CHECK THE ACCESS LEVEL OF THE USER... FIND WHICH ARRAY USER IS IN
    function check_access() {
        if (in_array("kaisersolze", $commDocsAdminUsers)){
          return "Match found in comDocsUsers Array";
        }
        else if (in_array($this->name, $commDocsAdminExecutiveUsers)){
              return "Match found in comDocsUsers Array";
        }
        else {
              return "No Access Allowed";  // USER NOT FOUND IN EITHER ARRAY
            }
        }
    } 

    // NOW LETS DO SOME STUFF WITH OUR NEW CLASS
    $currentUser = new userLogin(); // INVOKE THE NEW USER CLASS
    $currentUser->set_name("kaisersolze"); // SET NAME OF CURRENT USER

    print_r($currentUser); // SHOW THE FULL OBJECT $CURRENTUSER
    echo '<BR>-------------------------------------------------------------<BR>';
    echo $currentUser->get_name(); // ECHO OUT THE NAME FOR THE $CURRENTUSER
    echo '<BR>--------------------------------------------------------------<BR>';
    echo $currentUser->check_access(); // CHECK TO SEE WHICH ARRAY THE USER IS IN

?>

如何从班级成功运行in_array?

1 个答案:

答案 0 :(得分:1)

$ commDocsAdminUsers $ commDocsAdminExecutiveUsers 设置为全局变量或类的属性。

class userLogin {

    public static $commDocsAdminUsers = array("kaisersolze", "bennyblanco", "carlitobrigante", "ashylarry", "claytonbigsby");
    public static $commDocsAdminExecutiveUsers = array("waltjr", "skylerwhite", "tuco", "skinnypete", "walterwhite");


    // ALLOWS US TO CHECK THE ACCESS LEVEL OF THE USER... FIND WHICH ARRAY USER IS IN
    function check_access() {
        if (in_array("kaisersolze", self::commDocsAdminUsers)){
          return "Match found in comDocsUsers Array";
        }
        else if (in_array($this->name, self::commDocsAdminExecutiveUsers)){
              return "Match found in comDocsUsers Array";
        }
        else {
              return "No Access Allowed";  // USER NOT FOUND IN EITHER ARRAY
            }
        }
    }