Re: PHP5 Inheritance/method override problem

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Edward Kay wrote:
Hi Richard,

This is very strange. I can certainly reproduce the problem. Putting a
var_dump($this) in ClassA's save method shows that PHP sees $this as an
instance of ClassB - when it should be of ClassA.
what *you* think it should be and what php's developers decided
it should be
about 3+ years ago obviously differ.

if you have an instance of ClassB it is exactly that - refering to $this
in the parent class definition won't magically make the class of
the instance change.

$this is plain this and not something else.

Yes, you are indeed correct.

I was thinking that as B extends A, A wouldn't know anything about B thus
$this in A would refer to A. I can now see that my logic was flawed here.
Thanks for pointing it out Jochem!

Richard, replacing your

  if ($this->exists($value))

with

  if (self::exists($value))

will call A's exists method, as you require. As Brad pointed out however,
your defintion of B overrides A's exists method. If you need both, then you
should rename the method in class B.

Edward


Using the self::exists(...) call instead of $this->exists(...) worked perfectly. It threw me for a loop to see ClassA call a method in ClassB even though ClassA has no reference to ClassB at design time. It is probably why in other languages like C++ they use the virtual keyword to identify this behaviour.

Can self::method(...)/self::$variable replace $this->method(...)/$this->variable in all uses or are there cases where you would need to use $this instead of self?

In another post Roman said that all non-private method are virtual in PHP. If this is the case, I am assuming that the PHP architects would want developers to use self:: in classes that could be subclassed with method names that are the same as the parent(s)?

Thanks all for the help.

--
Richard Morris
HDD Broker, Inc.

    Toll-Free: +1 866 960-3331
International: +1 250 474-6022
          Fax: +1 250 474-6099
       E-Mail: richard@xxxxxxxxxxxxx
     Web Site: www.hddbroker.com

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux