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 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥200 求能开发抖音自动回复卡片的软件
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题
  • ¥50 C#编程中使用printDocument类实现文字排版打印问题
  • ¥15 找会编程的帅哥美女 可以用MATLAB里面的simulink编程,用Keil5编也可以。