Backend Development 2 min read

Difference Between view() and fetch() Methods in ThinkPHP5 Controllers

The article explains the distinctions between the view() helper and the fetch() method in ThinkPHP5 controllers, showing code examples for both inherited and non‑inherited controllers, discussing how they handle common template configurations, and recommending the preferred usage in projects.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Difference Between view() and fetch() Methods in ThinkPHP5 Controllers

In ThinkPHP5 (TP5) controllers there are two main ways to render templates: using the view() helper function and the fetch() method, each with slightly different behavior.

When the controller does not inherit from the base controller, you can either instantiate a view object and call its fetch method:

<code>// not inheriting controller
$view = new view();
return $view->fetch('index/demo');</code>

or use the global view() helper directly:

<code>// not inheriting controller
return view('index/demo');</code>

If the controller extends the TP5 base controller, you can call fetch directly on $this :

<code>// inheriting controller
return $this->fetch('index/demo');</code>

The latter two approaches (the helper view() and the inherited $this->fetch() ) support common configuration replacements such as tpl_replace_string (e.g., __CSS__ ) in templates, allowing paths and other variables to be injected automatically, whereas the first approach outputs the raw string.

For consistency and to leverage shared configuration, the article recommends using the helper view() or the inherited $this->fetch() in projects.

When you instantiate a view object directly, it cannot read the common configuration file; you must manually set parameters after creating the object, for example:

<code>new view();</code>
backendfetchPHPControllerview()ThinkPHP5
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.