note 80204 added to language.oop.constructor
| From: | anthop at light-within dot org | Date: | Fri, 04 Jan 2008 06:01:29 +0000 |
| Subject: | note 80204 added to language.oop.constructor | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-134755@lists.php.net to get a copy of this message | ||
@ 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.
----
Server IP: 208.69.120.35
Probable Submitter: 76.104.183.103
----
Manual Page -- http://www.php.net/manual/en/language.oop.constructor.php
Edit -- https://master.php.net/note/edit/80204
Del: integrated -- https://master.php.net/note/delete/80204/integrated
Del: useless -- https://master.php.net/note/delete/80204/useless
Del: bad code -- https://master.php.net/note/delete/80204/bad+code
Del: spam -- https://master.php.net/note/delete/80204/spam
Del: non-english -- https://master.php.net/note/delete/80204/non-english
Del: in docs -- https://master.php.net/note/delete/80204/in+docs
Del: other reasons-- https://master.php.net/note/delete/80204
Reject -- https://master.php.net/note/reject/80204
Search -- https://master.php.net/manage/user-notes.php