dongqiu7365 2017-11-27 14:50
浏览 115
已采纳

从不同的控制器调用时,PHP / Laravel父类变量为null

Parent Class:

<?php

namespace App\Services;

class RequestVariables {

    protected static $keys_tour;

    public static function init() {

    self::$keys_tour = array_flip(['tour_type', 'city_from']);

    }

}

Child Class:

<?php

namespace App\Services;

class PreviousVersions extends RequestVariables {

       public static function createVersion ($tour) {

            dd(parent::$keys_tour);

  }
}

When I call PreviousVersions::createVersion() from 1st controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;    

use App\Services\PreviousVersions;

use App\Tour;

class Tours2Controller extends Controller

{

    public static function PreProcess($tour)

    { 

        PreviousVersions::createVersion($tour);
    }

}

it outputs what's expected:

array:2 [
  "tour_type" => 0
  "city_from" => 1 ]

but when I execute the same function in another controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Tour;

use App\Services\PreviousVersions;


class BookingController extends Controller {

    public function booking($tour)

    {

      PreviousVersions::createVersion($tour);

    }

}

it outputs 'null'

I can't see what's different between my controllers causing different results when calling the same method. Can somebody tell me why it outputs 'null' in the 2nd case?

If you need more information, please ask.

  • 写回答

1条回答 默认 最新

  • dqh19413 2017-11-27 15:40
    关注

    The $keys_tour property is being set inside the init() method of the RequestVariables class.

    You can solve it by calling RequestVariables::init() inside the createVersions() method:

    public static function createVersion ($tour)
    {
        RequestVariables::init();
    }
    

    Or using the parent keyword:

    public static function createVersion ($tour)
    {
        parent::init();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥15 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏