gpt4 book ai didi

php - 初学者...对同一函数中的同名变量感到困惑

转载 作者:行者123 更新时间:2023-12-03 23:05:58 26 4
gpt4 key购买 nike

 1   <?php  
2 class ACL
3 {
4 var $perms = array(); //Array : Stores the permissions for the user
5 var $userID = 0; //Integer : Stores the ID of the current user
6 var $userRoles = array(); //Array : Stores the roles of the current user
7
8 function __constructor($userID = '')
9 {
10 if ($userID != '')
11 {
12 $this->userID = floatval($userID);
13 } else {
14 $this->userID = floatval($_SESSION['userID']);
15 }
16 $this->userRoles = $this->getUserRoles('ids');
17 $this->buildACL();
18 }

这是我正在学习创建登录系统的教程的一部分。我不知道我是不是在这太久了,我的大脑被炸了,但我对在函数 __constructor 中用作参数的 boolean 语句感到困惑。参见第 8 行。

这是教程给出的解释:

The __constructor() function is used to initialize the object when we want to load an ACL. It is called automatically when we call new ACL();. It is then passed a single, optional argument of the user to load the ACL for. Inside the constructor, we check to see if a user ID was passed in. If no ID was passed, we assume that we will load the ACL for the currently logged in user; so we read in the session variable for that. Alternatively, if we pass in a user ID, it allows us to read and edit the ACL for a user other than the one logged in (useful for your admin page).

问题 #1... 所以这个方法会在您创建一个新类时立即启动,并且它会将 boolean 值作为参数。我不明白为什么您需要声明 userID = ' '。难道你不能让它更简单并写成: function __constructor($userID) { if ($userID != '') ......等等。 ETC。 ??或者他们的意思是一样的?陈述一个 boolean 值的想法对我来说从来没有意义,特别是当你没有在 IF 语句中使用它来测试它的有效性时。

编辑:我犯了一个非常奇怪的错误。对不起,忽略整个 boolean 值,它甚至不是 boolean 语句。我的错误……12 小时的编程学习正在付出代价。

问题2:第5行的变量$userID和第8行的$userID是一样的吗?我想不,但我不确定。我确定第 5 行的 $userID 与第 12 行和第 15 行的 $this->userID 相同,但第 8 行和第 10 行的情况如何?我很困惑。如果第 8 行的变量 $userID 不为空,那么您将第 5 行找到的 $userID 分配给第 8 行 $userID 的 floatval?我有一种感觉,这些是 2 个不同的 $userID。如果是这样的话,为什么这个人不能使用不同的词呢?哈哈

注意:我学习 PHP 还不到一周,所以这些问题看起来更像是基本的概念性问题。语法对我来说不是真正的问题,而是概念。

感谢任何帮助。干杯。

最佳答案

好的,

  1. 不是每次“创建新类”时都使用该方法,而是每次实例化 时调用它,这意味着每次 new ClassName()语句被调用。原因function __construct($userID = '')使用而不是 function __construct($userID) , 是因为我们要给它一个默认值。这意味着用户可以调用 new APC()new APC("userID") .
  2. 没有。第 5 行声明的是一个对象属性,它是存在于每个对象中的一个变量(这意味着如果您实例化 2 个 APC 类,您将为每个创建的对象创建一个变量,总共 2 个)。
    第 8 行的那个是一个函数参数。当使用参数 ( new APC("userID") ) 调用该方法时,该参数将存储在函数内部的该变量中。
    巧合的是他们两个同名。

关于php - 初学者...对同一函数中的同名变量感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9452270/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com