douqiao1983 2014-03-07 00:16
浏览 52
已采纳

从空值创建默认对象(在Laravel中为新用户添加项目到数据库)

I have a function I am using to add

I have an array $data that contains the user data I am trying to put into the db. Everything works except for the "makeUrlTag" function portion:

public function makeUrlTag() {

        $url_tag = '';
        if(isset($this->data['user']['first_name'])) {
        $url_tag = $url_tag . $this->data['user']['first_name'];
        }
        if(isset($this->data['user']['last_name'])) {
        $url_tag = $url_tag.$this->data['user']['last_name'];
        }

        $fan->url_tag = $url_tag;

    }

public function createFan() {
        $fan                        = new Fan;
        $fan->fbid                  = isset($this->data['user']['id']) ? $this->data['user']['id'] : '';
        $fan->email                 = isset($this->data['user']['email']) ? $this->data['user']['email'] : '';
        $fan->first_name            = isset($this->data['user']['first_name']) ? $this->data['user']['first_name'] : '';
        $fan->last_name             = isset($this->data['user']['last_name']) ? $this->data['user']['last_name'] : '';


        $this->makeUrlTag();

        $fan->save();
    }

I call createFan with:

$this->createFan();

When I run this, I get the error:

Creating default object from empty value

in reference to the makeUrlTag(); portion. Particularly the line:

$fan->url_tag = $url_tag;

Any idea what's going on here? Again, taking out the makeUrlTag portion works fine. Thank you.

  • 写回答

1条回答 默认 最新

  • dsapkqaduj6718493 2014-03-07 01:08
    关注

    It's because your makeUrlTag() method doesn't know about the Fan which is in the $fan variable you created in the createFan() method and trying to use a non-existing object in the scope of makeUrlTag() method using this:

    $fan->url_tag = $url_tag;
    

    So, you need to make your $fan object available to makeUrlTag() and to do this you may add a protected property in your class:

    class YourClass {
    
        protected $fan = null;
    
        public function makeUrlTag(){
    
            $url_tag = '';
    
            // ...
    
            $this->fan->url_tag = $url_tag;
    
        }
    
        public function makeUrlTag(){
    
            $this->fan = new Fan;
    
            // rest of your code
            // but use $this->fan instead of $fan
    
            $this->fan->save();
    
        }
    
    }
    

    So, now you can access the $fan object from any method of your class ussing $this->fan, that's it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘