【问题标题】:Can codeigniter support Inline functions.?codeigniter 可以支持内联函数吗?
【发布时间】:2014-11-14 12:58:53
【问题描述】:

我们可以在 Codeigniter 的另一个函数中编写多个函数吗?这是我的控制器

class Products extends CI_Controller {

  public function myproduct() {
      $this->load->view('myproduct'); // call myproduct.php

           public function features() {
              $this->load->view('features');  // call "myproduct/features"
            }

           public function screenshots() {
              $this->load->view('screenshots');  // call "myproduct/screenshots"
            }
    }
}

根据我的控制器,myproduct() 中有 2 个内联函数。我的目标是将网址显示为

localhost/mysite/products/myproduct
localhost/mysite/products/myproduct/features
localhost/mysite/products/myproduct/screenshots

我已经尝试过了,但它给了我一个错误

Parse error: syntax error, unexpected 'public' (T_PUBLIC) in D:\...........\application\controllers\mysite\products.php on line 5

第 5 行是

public function features() { .........

【问题讨论】:

  • 为什么需要函数内部的函数?
  • myproduct 方法中获取参数并根据条件求解。你不能在里面添加任何方法,
  • 不,您将无法在方法中加载方法,而且您真的不想这样做。你到底想从中得到什么?

标签: php codeigniter inline-functions


【解决方案1】:

您可以将其视为 url 中的 uri 参数:

public function myproduct($param = null) 
{
    if($param == null) {
        $this->load->view('myproduct'); 
    } elseif($param == 'features') {
        $this->load->view('features');
    } elseif ($param == 'screenshots') {
        $this->load->view('screenshots');
    }
}

【讨论】:

    【解决方案2】:

    这不是 codeigniter 中的东西...这在 PHP 中通常是不可能的。您可以使用闭包,但它们不会在您的情况下呈现所需的效果。

    尝试阅读CodeIgniter URI Routing 以了解codeigniter 中的路由原理。而不是在控制器中创建单独的函数。

    【讨论】:

      【解决方案3】:

      我不确定您要达到什么目的或计划如何调用/使用这些函数以及在哪个范围内,但为了在函数中声明函数,您可以这样做:

      public function myproduct(){
      
          $t = 'myproduct';
      
          $features = function($t = '', &$this = ''){
              // some code goes here
      
              $this->load->view('features'); // will NOT work
      
              $this->load->view($t.'/features'); // this should work
          };
      
          $features($t, $this); // load the features view
      
      }
      

      这应该是你的目标:

      public function myproduct($uri_piece = ''){
      
          $this->load->view('myproduct/'.$uri_piece);
      
      }
      

      【讨论】:

      • 我认为$this$t 都不在匿名函数的范围内。
      猜你喜欢
      • 2010-09-16
      • 1970-01-01
      • 2011-08-24
      • 2020-03-07
      • 2017-10-24
      • 2014-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多