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) {
        ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度