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 一道python难题2
  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备