Backend Development 9 min read

Understanding Controller Instantiation, ArrayAccess, and Magic __get in the ThinkPHP Framework

This article provides a detailed walkthrough of how ThinkPHP instantiates controllers after route detection, explains the role of the Dispatch module, and compares the behavior of ArrayAccess versus the magic __get method for accessing container services, illustrating each step with code examples.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding Controller Instantiation, ArrayAccess, and Magic __get in the ThinkPHP Framework

The article, contributed by the PHP Chinese community author "Kaka", analyzes the process of controller instantiation in ThinkPHP, using it as a case study to explain the differences between ArrayAccess and direct magic method access.

After a detailed review of routing, the route rule used is Route::get('hello/:name', 'index/index/:name'); . The routing dispatch returns an instance of think\route\dispatch\Module , which is stored in the variable $dispatch .

The application entry file creates an App instance and calls its run method, which triggers the routing dispatch and eventually leads to controller instantiation.

Within the dispatch process, the code $dispatch->run() invokes the run method of the think\route\dispatch\Module class. This method calls $data = $this->exec(); , which ultimately resolves to the controller via $this->app->controller() .

The Dispatch class is abstract; the article shows how to locate its concrete subclass ( thinkphp/library/think/route/dispatch/Module.php ) and explains the two possible inheritance scenarios for abstract classes.

When accessing container services, using array syntax like $app['request'] triggers the ArrayAccess method offsetGet , while accessing an undefined property such as $this->hook invokes the magic method __get . Both pathways eventually call the container's make method to instantiate the required class.

The article concludes that whether using ArrayAccess or the __get magic method, ThinkPHP ultimately relies on the container's make method to return class instances, and it demonstrates this with several code snippets and screenshots.

routingMagicMethodsThinkPHPArrayAccess
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.