note 80204 deleted from language.oop.constructor by danbrown
| From: | danbrown@php.net | Date: | Sat, 07 Nov 2009 18:56:57 +0000 |
| Subject: | note 80204 deleted from language.oop.constructor by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-162519@lists.php.net to get a copy of this message | ||
Note Submitter: anthop at light-within dot org
----
@ alexey:
My background has also been in more strongly-typed, object oriented languages like Java and C#, so
learning PHP has been extremely frustrating at times. Sometimes it feels like PHP is completely the
wrong tool for the job (like using a chainsaw to perform brain surgery).
The phenomenon you're describing, I think, is a part of a larger difference in how PHP treats
the $this variable. It's defined as the first instance of an object it comes across. PHP(4)
is really a scripting, functional language so when the child was calling it's parent's
constructor in your example, it wasn't really call a constructor, but simply just another
function. In fact, the two classes don't even have to be related:
<?php
class test_class_1 {
var $v;
function printV1() {
echo $this->$v, "<br />";
}
}
class test_class_2 {
var $v;
function printV2() {
test_class_1::printV1();
}
}
$c1 = new test_class_1();
$c2 = new test_class_2();
$c1->$v = 1;
$c2->$v = 2;
test_class_1::printV1();
$c1->printV1();
$c2->printV2();
?>
The output of this should be:
1
2
The first empty line break is due to the printV1 function being called statically, and thus the
$this-$v is undefined (though the line break still printed).
The "1" that was printed is from a straight-forward function call.
For the "2" that was printed, notice that the printV2 function correctly printed
$c2's $v value, even though it was calling printV1. test_class_1 isn't even the parent of
test_class_2. The $this variable just happened to point to the instance of test_class_2, and
test_class_2 just happened to have a defined $v variable.
One way to think of it is that all functions are basically just functions and that classes are
really just a way to help scope them.