dongqianchi0512 2015-10-06 18:06
浏览 26
已采纳

如何使用PHP将数组从方法传递给属性

Actually I want to change the color of current topic... Here is my CSS code:

.active{
    color: red;
    border-left: 1px solid red;
}

Also here is my PHP class:

class Languages
{
    public $active;
    public $data = '<div class="menu">
                        <ul>
                            <li $active["en"]>English</li>
                            <li $active["fr"]>French</li>
                        </ul>
                    </div>';

    function English()
    {
        // other codes
        $this->active["en"] = 'active';
        return $active;
    }

    function French()
    {
        // other codes
        $this->active["fr"] = 'active';
        return $active;
    }

}

But the above code does not work, why?! And how can I fix it?

  • 写回答

2条回答 默认 最新

  • douna2633 2015-10-06 18:12
    关注

    There are a few issues with your code. Firstly, using single quotes (') instructs PHP to NOT interpolate values. Secondly, I suspect that your data value will never actually update as the values in $active change. Also, you should be using class="active" not simply adding the word 'active' into your li element. A more effective solution may be something like the following

    class Languages
    {
        public $active;
    
        function English()
        {
            // other codes
            $this->active["en"] = 'active';
            return $active;
        }
    
        function French()
        {
            // other codes
            $this->active["fr"] = 'active';
            return $active;
        }
    
        function data()
        {
            return = '<div class="menu">
                            <ul>
                                <li class="' . $this->active["en"] . '">English</li>
                                <li class="' . $this->active["fr"] . '">French</li>
                            </ul>
                            </div>';
        }
    
    }
    

    Then you can access the generated html by calling the $object->data() method and your generated HTML will always reflect the current values in $active. Alternatively you could still store $data as a member variable and simply have a function that regenerates it with new values such as function updateData().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败