Re: PHP5 Inheritance/method override problem
| From: | Richard Morris | Date: | Wed, 06 Dec 2006 18:22:39 +0000 |
| Subject: | Re: PHP5 Inheritance/method override problem | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-245577@lists.php.net to get a copy of this message | ||
Edward Kay wrote:
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@hddbroker.com Web Site: www.hddbroker.comYes, 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. EdwardHi 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.