19
I found this little code inside the folder Composer/ClassLoader.php
, in a project where I use the composer
.
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*/
function includeFile($file)
{
include $file;
}
The translated comment could be:
Isolated scope for
include
. Prevents access to$this
andself
Testing
Taking into account the case cited above, I realized that in Laravel 4, I have access to $this
in any view!
And see what happens in the following code in any view:
@extends('layout.default')
<?php
$this->compiler = 1;
?>
The following error is generated
Call to a Member Function isExpired() on a non-object
And the interesting detail is that, like the include
would be directly in the class method, I was able to access a property of type protected
and give it an unexpected value for the framework!
In other frameworks, such as Zend
, the $this
can also be accessed at view
.
Questions
So then I came up with some questions:
What would be other possible problems caused by a
include
within the class and have access to$this
- in addition to the aforementioned?In a MVC structure, in the class representing
view
I should leave free access to$this
, or use another class to "be the$this
" view, or something else?When it would be recommended to enclose the function
include
and when not (always, never or in most cases)?
If you think I’ve removed too many tags feel free to add them again =)
– Oeslei
I believe that in the codes themselves in a project there is no problem in having access to
$this
because, with some exceptions, we do not use the variable$this
in the global scope... However, for code shared between projects it is always important to keep variables and methods that can break the functioning well protected not to suffer unexpected surprises.– Oeslei
Here is the commit from the Poser that introduced this function: https://github.com/composer/composer/commit/6d7b9afc4b6bd1bc640b4c2b803c7a87f5a59dd9
– gmsantos
The problem I see is having access to methods
private
andprotected
directly.– Guilherme Nascimento
I will continue to be insistent. I think there is still something missing to solve this question
– Wallace Maxters