doupai5450
2017-09-07 05:33
浏览 179
已采纳

Php Laravel在同一模型中调用一个函数

I have a model with 2 functions. Let's say the model's name is Cars. I am trying to call one function brand that returns an array so I can use it inside the other getBrand function.

public static function getBrand($data) {
    $brandVariable = $this->brand(); 
    for ($i=1; $i < count($brandVariable ) ; $i++) { 
        //do something
    }
}

public static function brand() {
    $arrayValues = array(
         1 => 'Brand A',
         2 => 'Brand B',
    );
    return arrayValues;
}

Since the values are in brand function, I need to pass it inside getBrand.

I am getting an error in the for loop. I tried in another file (local PHP not Laravel) and it is working fine. But in Laravel, it is not getting the expected result.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dop20345 2017-09-07 05:36
    已采纳

    Use Cars::brand because you declared functions as static

    public static function getBrand($data=null) {
        $Cars = new Cars();
        $brandVariable = $Cars::brand(); 
        for ($i=1; $i < count($brandVariable ) ; $i++) { 
            //do something
        }
    }
    

    Live demo : https://eval.in/856708

    Or

    public static function getBrand($data=null) {
        $brandVariable = Cars::brand(); 
        for ($i=1; $i < count($brandVariable ) ; $i++) { 
            //do something
        }
    }
    

    Live demo : https://eval.in/856712

    已采纳该答案
    打赏 评论
  • donglizuo8892 2017-09-07 05:38

    You are calling brand inside a static function and $this is not available inside the methods declared as static.

    Since brand is declared as a static function you can use one of the following methods to call the function

    if within the class

    self::brand();
    

    or

    static::brand();
    

    from outside of the class

    ClassName::brand();
    
    打赏 评论
  • dri8163 2017-09-07 05:49

    the functions are static so you should use

    self::brand()

    instead of

    $this->brand()

    打赏 评论

相关推荐 更多相似问题