Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return statement in file doesn't stops class definition?

As stated here php.net/return, there is an option to stop executing include with 'return' statement.

Who can tell me why this works as stated 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 this is true?

When test2.php is changed to any other form of code execute (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
like image 478
Adam Avatar asked Dec 20 '22 15:12

Adam


1 Answers

Return ends execution, but does not stop the include.

In the first case, the file is included, and execution stops after the return and control is given back to test1.php. But the class is included, and therefore class_exists returns true. So case 1 works as expected.

In the second case, by using the curly braces, the class definition becomes part of the execution. The return ends execution of the include, before the class is defined.

like image 200
JvdBerg Avatar answered Jan 10 '23 20:01

JvdBerg