【问题标题】:Can someone explain to me how $_POST['var1'] is assigned to $m_value at this example有人可以向我解释 $_POST['var1'] 在此示例中如何分配给 $m_value
【发布时间】:2021-12-16 02:41:43
【问题描述】:
<?php 
    // set a value for this example, but imagine the user 
    // was posting this in a form.
    $_POST['var1'] = 'another_type'; 
    
    $valueObj = new class($_POST['var1']) {
        private $m_value;
    
        public function __construct(string $input)
        {
            switch ($input)
            {
                case 'type1' : $this->m_value = 1; break;
                case 'type2' : $this->m_value = 2; break;
                case 'another_type' : $this->m_value = 3; break;
                default : throw new Exception("Invalid input: $input");
            }
        }
    
        public function getValue() : int { return $this->m_value; }
    };
    
    print $valueObj->getValue(); // 3
  

https://blog.programster.org/php7-0-anonymous-classes

我无法理解 $_POST['var1'] 在构造函数中是如何分配给 $m_value 的。

【问题讨论】:

    标签: php class anonymous


    【解决方案1】:

    创建对象时,__construct 函数首先执行。您在初始化对象时传递了 $_POST['var1'] ,即 new class($_POST['var1']) 并且在您的构造函数中根据条件 $this->m_value 分配了值,在您的情况下它将是 3 作为值是“另一种类型”;

    【讨论】:

      【解决方案2】:

      $_POST['var'] 未分配给 $m_value

      创建类时,使用$_POST['var'] 参数对其进行实例化,该参数又作为$input 传递给__construct 类构造函数。

      然后将$input 的值传递给switch 语句,然后将3 的值分配给$m_value

      最后,$m_valuegetValue() 函数返回。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-05
        • 2011-05-08
        • 1970-01-01
        • 2012-04-12
        • 1970-01-01
        • 2012-04-09
        相关资源
        最近更新 更多