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.
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:
// not inheriting controller
$view = new view();
return $view->fetch('index/demo');or use the global view() helper directly:
// not inheriting controller
return view('index/demo');If the controller extends the TP5 base controller, you can call fetch directly on $this:
// inheriting controller
return $this->fetch('index/demo');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:
new view();Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
