Sunday, January 3, 2010

require_once inside the method in php class

I've heard on some discussion list that if you have
require_once inside one of your methods in a php class then php will still evaluate
this require_once statement at compile time.

What these people were trying to say is that you should not have require_once or any other
similar statement inside your methods because it will slow down your script since php
will have to look at every such statement and make sure that there files are actually available.

I don't know, but I think it's a myth.

I took one of the classes from Zend, the Zend_Acl class
and inside the add() method there is a statement:

if (!$role instanceof Zend_Acl_Role_Interface) {
require_once 'Zend/Acl/Exception.php';
throw new Zend_Acl_Exception('addRole() expects $role to be of type Zend_Acl_Role_Interface');
}

So I just changed the require_once 'Zend/Acl/Exception.php';
to require_once 'nd/Acl/Exception.php';
This of cause points to non-existent php file, and would raise an error.

But php loaded my Acl class just fine. Not only it loaded my Acl class fine, but it even allowed
me to call the add() method. So as long as my script did not
pass this test: if (!$role instanceof Zend_Acl_Role_Interface)
php did not complain at all.

So there you have it, a proof that php does not care about your require_once statements until it actually executes these statements.

So, don't worry about this silly issue then - it is OK to have require_once inside the methods
but it's just as OK to completely rely on autoloader.

Personally I always use autoloader, so when I decided to use Zend_Acl class my first instinct was to just comment out all the require_once statements since they really hurt my eyes. Hey, I am not used to seeing require_once in my classes at all - that's what the spl_autoload and __autoload are for.

But then I though that I am going to be a good programmer and will not mess with an existing class - if I need some changes in the class, then I will extended like any good programmer should. And that what lead me to this test - I just wanted to be sure that having require_once inside the method will not cause any type of performance penalty. And it did not.

OK, I said too much already about this tiny issue.

Bye now.

No comments:

Post a Comment