Home > Mobile >  Codeigniter 4 How to call a controller method in a view?
Codeigniter 4 How to call a controller method in a view?

Time:12-17

I have a function with named pr in BaseController. I can access this function in my controllers but i want use this function in views too. Is there is a way ?

Controller File

view file

Edit: this is how i try to use pr in view.

 <div >
<?php

$this->pr("11", 22);

and my pr function is ;

 public function pr($array, $die = "", $type = "")
    {
        ini_set("xdebug.var_display_max_children", '-1');
        ini_set("xdebug.var_display_max_data", '-1');
        ini_set("xdebug.var_display_max_depth", '-1');

        echo "<pre>";
        if (!$type) print_r($array);
        else var_dump($array);
        echo "</pre>";
        if ($die) die();
    }

CodePudding user response:

You're calling pr wrong:

  1. pr is a method in your \App\Controller\Home class. So it should be \App\Controller\Home::pr(). Instead, you were calling \CodeIgniter\View\View::pr().

  2. Views are probably rendered in to some \CodeIgniter\View\View class instance, hence calling $this in a view results in calling \CodeIgniter\View\View::pr(). That's why a $this->pr() call isn't working as you expected.

  3. Your Home::pr() is an ordinary method, which can only be called within the instance (i.e. through $this inside an instance). Your view do not have access to it.

  4. It seems your pr is not doing anything specific to the Controller instance (i.e. not using $this inside), you can simply rewrite it as a public static method, which can easily be called in your view.

So, this is probably useful for you.

Controller:

namespace App\Controllers;

...

class Home {

    ...

    public static function pr($array, $die = "", $type = "")
    {
        ini_set("xdebug.var_display_max_children", '-1');
        ini_set("xdebug.var_display_max_data", '-1');
        ini_set("xdebug.var_display_max_depth", '-1');

        echo "<pre>";
        if (!$type) print_r($array);
        else var_dump($array);
        echo "</pre>";
        if ($die) die();
    }

    ...

}

View:

 <div >
 <?php \App\Controllers\Home::pr("11", 22); ?>
  • Related