dongzhong7299 2014-10-24 13:49
浏览 49
已采纳

使用方法参数绑定外部变量和Class受保护字段

How to implement this kind of functionality:

  • Fill entity eg. Member with data
  • Bind Member to form with $form->bind($member) to private property _formData
  • Afterward do some stuff inside $form, eg. $form->validate() with _formData
  • $member should be also changed as _formData is changed.

    class Form {
    
        private $_formData;
    
        function bind1(&$row) {
            // this change member outside
            $row['full_name'] =
                $row['first_name']
                . ' ' .
                $row['last_name'];
        }
    
        function bind2(&$row) {
            $this->_formData = $row;
            // this will not change memeber
            $this->_formData['full_name'] =
                $this->_formData['first_name']
                . ' '
                . $this->_formData['last_name'];
        }
    }
    
    $member = array('full_name' => null, 'first_name'=>'Fn', 'last_name' => 'Ln');
    $form = new Form();
    
    $form->bind1($member);
    var_dump($member['full_name']);
    // output: 'FnLn'
    
    $form->bind2($member);
    var_dump($member['full_name']);
    // output: null
    

Method validate work with private _fieldData, so this to work bind2 test should work.

  • 写回答

2条回答 默认 最新

  • dqef7931 2014-10-24 14:16
    关注

    What you are trying to do is possible, but you need to set a reference of the reference in the bind1 and bind2 method, like this:

    $this->_formData = & $row;
    

    You are also making misspellings between full_name and fullName as array keys. For example in the bind2 method:

    $this->_formData['full_name'] =  $this->_formData['first_name'] . ' ' . $this->_formData['last_name'];
    

    And in your test-code you var_dump full_name. Chaging full_name in bind2 to fullName should fix your issue.

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

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧