doqp87012 2015-06-16 14:35
浏览 25

PHP - 可以预定义变量(不是类的属性)以在方法中使用吗?

Simple example

I would like to know if there is any possible way that $data could already exist without being set in that method, and if so how to set it.

public function index(){

   if(isset($data)){
       //how is this possible?

   } else if(isset($this->data){
       // set in parent::__construct
       // ok i'm going to have to set $data in every method in every controller
       $data = $this->data;
   }
}

additional info

This is my specific problem,

I am using a framework with a controller class which is extended for every controller.

class ControllerBlog extends Controller {}

Every method in every controller perform a few almost identical tasks. Some of these tasks return data within the scope of the method called.

//e.g
public function index(){
    $this->loadthis('blog');
     $this->loadthat('blog');

    $data = $this->get_this('blog');

     ... 
     ...
    $data['title'] = 'blog title';

     use_data($data);
}

I would like to move these tasks to Controller class function __construct to limit the amount of code repeated.

<?php
    class Controller {

        public function __construct() {
            //load this and that and return data;
            $data = $this->load_and_return_all(get_class($this));

            //class level
            $this->data = $data;
        }
    }

is there a way to get the $data variable for use within the scope of the method without the need of adding any additional code to every method of every controller?

class ControllerBlog extends Controller {

   public function index(){ 

      //adding this to every method seems silly
      $data = $this->data;
      // i would like $data to be set in the construct;
   }
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 simulink单相桥式整流电路
    • ¥35 问问51单片机流水灯的代码该怎么写
    • ¥15 关于#百度#的问题:感觉已经将字体段落、字体、页边距、纸张大小、文档网络调成与论文模板一致,为什么黄色部分字体左右的间距还是不一样啊,求私信发文件接收看一下
    • ¥15 stata webuse报错
    • ¥15 TypeError: Cannot read properties of undefined (reading 'status')
    • ¥15 如何利用AI去除图片中的竹架子
    • ¥15 python 写个基金爬取的代码,自动卖出功能
    • ¥15 Linux系统启动不起来
    • ¥15 为什么运行仿真数码管不亮(语言-c语言)
    • ¥15 陈仁良《直升机飞行动力学》小扰动线化方程如何推导