【问题标题】:Laravel Non-static method issueLaravel 非静态方法问题
【发布时间】:2013-01-02 17:46:40
【问题描述】:

拥有以下型号:

news.php

class News extends Aware {

    public static $table = 'noticia';
    public static $key = 'idnoticia';
    public static $timestamps = false;

    public static $rules = array(
        'titulo' => 'required',
        'subtitulo' => 'required',
    );

    public function images()
    {
        return $this->has_many('Image');
    }
}

image.php

class Image extends Aware {

    public static $timestamps = true;

    public static $rules = array(
        'unique_name' => 'required',
        'original_name' => 'required',
        'location' => 'required',
        'news_id' => 'required',
    );

    public function news()
    {
        return $this->belongs_to('News');
    }

}

然后在控制器中我执行以下操作:

$image = new Image(array(
    'unique_name' => $fileName,
    'original_name' => $file['file']['name'],
    'location' => $directory.$fileName,
    'news_id' => $news_id,
));
News::images()->insert($image);

我不断收到以下错误消息:

非静态方法 News::images() 不应该被静态调用, 从不兼容的上下文中假设 $this

任何想法我做错了什么?

似乎不需要设置public static function images(),因为刷新后我收到一条错误消息

$this 不在对象上下文中时

Gordon 说通过 News::images()->insert($image); 我正在做一个静态调用,但这就是 saw 的做法

【问题讨论】:

    标签: php model laravel non-static


    【解决方案1】:

    您缺少一些步骤。

    图片属于新闻,但您没有引用要更新的新闻帖子。
    您可能想要这样做:

    $image = new Image(array(...));
    $news = News::find($news_id);
    $news->images()->insert($image);
    

    更多内容请关注docs。

    【讨论】:

      【解决方案2】:

      您在名为statically 的函数中使用$this。这是不可能的。

      $this 仅在您使用new 创建实例后才可用。

      如果你打开严格模式你会得到另一个错误,即images不是一个静态函数,因此不应该被静态调用。

      问题出在News::images(),而不是images()->insert($image);

      【讨论】:

      • 和我对 Martin 说的一样,我知道...我按照别人的要求尝试过,尽管知道会出现上述问题。
      【解决方案3】:

      $this 只能在对象实例中使用。 Class::method() 调用指定类的静态方法。

      在你的情况下,你混合了两者。

      您对图像的函数定义是针对对象实例的:

      public function images()
      {
          return $this->has_many('Image');
      }
      

      您将其称为静态方法:

      News::images()->insert($image);
      

      News 类需要被实例化或修改 images 方法以支持静态调用。

      【讨论】:

      • 如果你没有注意到...我说过我曾尝试过使用public static...,因为我建议这样做,但显然会遇到上述问题
      • 是的,所以我提到你只能在对象实例中使用$this。
      猜你喜欢
      • 1970-01-01
      • 2020-12-27
      • 2023-02-22
      • 2018-05-30
      • 2016-09-19
      • 2015-06-23
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      相关资源
      最近更新 更多