Does the return statement in a file not stop class definition?

As indicated here by php.net/return , it is possible to terminate the include statement with the return statement.

Who can tell me why this works as below

//test1.php

include 'test2.php'; var_dump(class_exists('TestClass_ShouldntBeDefined')); 

//test2.php

 return; class TestClass_ShouldntBeDefined { } 

// run

 $ php -f test1.php bool(true) 

Why is this so?

When test2.php changes to any other form of code execution ( if(true) { ... } )

 return; { class TestClass_ShouldntBeDefined { } } 

then it works as expected

 $ php -f test1.php bool(false) 


PHP version

 $ php -v PHP 5.4.7 (cli) (built: Sep 13 2012 04:20:14) Copyright (c) 1997-2012 The PHP Group Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies with Xdebug v2.2.1, Copyright (c) 2002-2012, by Derick Rethans 
+4
source share
2 answers

Return completes the execution, but does not stop the inclusion.

In the first case, the file is included, and execution stops after returning and control returns to test1.php . But the class is included, so class_exists returns true . Therefore, case 1 works as expected.

In the second case, using curly braces, the class definition becomes part of the execution. Return completes the include before the class is defined.

+9
source

Classes and functions are not part of the sequential execution of the script. The return statement completes sequential execution, not oop execution.

+2
source

Source: https://habr.com/ru/post/1439318/


All Articles