douzi115522 2018-10-27 08:38
浏览 50
已采纳

在可从控制器访问的单独php文件中创建自定义函数

I want to write a function for catalog->controller->checkout->cart.php in Opencart 2.3.0.2 I have already written a logic to check priduct_id and action to be taken if particular product id is found. Now I want to take this logic in separate function in separate php file so that it will become more manageable.

I created function in php file under system->helper and loaded it from startup.php. Then I can call this function from cart.php but reference to variable $this is lost even if I am passing $this to this function.

My stripped down code looks like this cart.php

//some code before this
  if (!$json) {
                // Check if Product is Addon
                 test($this);
        //more code after this

customfunction.php

    function test($this) {  
    // print_r("Test Called");
    $temp = $this->request->post['product_id'];
    if ($this->request->post['product_id'] == 142) {
                    $json['success']   = sprintf($this->language->get('text_success'), $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']), $product_info['name'], $this->url->link('checkout/cart'));
                    $product_options   = $this->model_catalog_product->getProductOptions($this->request->post['product_id']);
                    $product_option_id = $product_option['product_option_id'];
//more code

I am getting error for

$this->request->post['product_id'];

Can someone tell me how to call custom function from separate php file preserving reference to $this variable.

  • 写回答

1条回答 默认 最新

  • dongxianghui3709 2018-10-27 08:53
    关注

    $this is reserved word in php:

    The pseudo-variable $this is available when a method is called from within an object context.

    Try that instead:

    function test($ctrl) { 
        $temp = $ctrl->request->post['product_id'];
        if ($ctrl->request->post['product_id'] == 142) {
        ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!