【问题标题】:Error in access function variable as static variable访问函数变量作为静态变量时出错
【发布时间】:2016-06-03 07:15:35
【问题描述】:

在我的演示项目中,我想访问某个类的静态变量,但这些变量名是动态传递的。我正在尝试使用如下所示的函数变量:

public function filterBy($params)
    {
        foreach ($params as $key=>$value) {
            $filter_field_name = strtoupper($key);
            $this->criteria->add(ProductPeer::$filter_field_name, $value, Criteria::EQUAL);
        }
        return $this;
    }

它给了我错误

致命错误:访问未声明的静态属性: ProductPeer::$filter_field_name in /home/sfprojects/shopme/lib/product/ProductDb.php 在第 47 行

虽然如果我使用ProductPeer::STATUS 而不是ProductPeer::$filter_field_name 那么它可以工作。

这里有什么问题?

【问题讨论】:

    标签: php oop static


    【解决方案1】:

    有一个函数constant()可以做到这一点:

    constant('ProductPeer::' . $filter_field_name);
    

    【讨论】:

    • 是的,完美!谢谢。虽然我不知道背后的原因,但如果你能通过常量函数说出访问背后的原因,那将会很有帮助
    • 我想$ 只访问类的属性,而常量是一个单独的语言结构,工作方式不同。
    【解决方案2】:

    $this->criteria->add(ProductPeer::$$filter_field_name, $value, Criteria::EQUAL);

    使用双美元符号作为其他变量的引用。像 $$filter_field_name

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多