On Wed, Mar 11, 2009 at 4:40 PM, Olivier Doucet <webmas...@ajeux.com> wrote:

> Hi,
>
>
>> not sure if this was mentioned on the general list but, i believe what
>> youre describing is documented in the manual under php5 classes/objects ->
>> "the basics":
>>
>> http://www.php.net/manual/en/language.oop5.basic.php
>>
>> $this is a reference to the calling object (usually the object to which
>> the method belongs, but can be another object, if the method is called
>> statically <http://www.php.net/manual/en/language.oop5.static.php> from
>> the context of a secondary object).
>>
>> -nathan
>>
> I know this behaviour is fully documented, but I was more concerned about
> "is it a 'normal' behaviour ?". How can a programmer controls the class he
> wrote, and make it absolutely bugproof ? How can he detect his function was
> called in a static context and forbid it (or write specific code for) ?
>

well, the access to $this of the secondary object is limited.  so the only
way it really does anything useful is if member variables you wish to access
are marked as public; making it mostly useless imo..  but anyway all youd
need to do is mark member vars as protected or private. (personally, i think
it should be able to access protected vars, since the class which invokes
the other statically is essentially sanctioning access to its instance
variables).

<?php
class A {
    public function showOtherClassInstanceVar($varname) {
        var_dump($this->$varname);
    }
}

class B {
    public $a = 1;
    protected $b = 2;
    private $c = 3;

    public function dumpViaMixin() {
        A::showOtherClassInstanceVar('a');
        A::showOtherClassInstanceVar('b');
        A::showOtherClassInstanceVar('c');
    }
}

$b = new B();
$b->dumpViaMixin();

---
outputs
int(1)

then the error log shows,

[11-Mar-2009 17:01:03] PHP Fatal error:  Cannot access protected property
B::$b in /Users/nnobbe/testDelegation.php on line 5
[11-Mar-2009 17:01:03] PHP Stack trace:
[11-Mar-2009 17:01:03] PHP   1. {main}() /Users/nnobbe/testDelegation.php:0
[11-Mar-2009 17:01:03] PHP   2. B->dumpViaMixin()
/Users/nnobbe/testDelegation.php:22
[11-Mar-2009 17:01:03] PHP   3. A->showOtherClassInstanceVar()
/Users/nnobbe/testDelegation.php:16

so you should be able to protect your classes w/o too much trouble.

-nathan

Reply via email to