This is a discussion on Strange problem in class creation within the PHP General forums, part of the PHP Programming Forums category; Hi all, I have encountered a "tricky" problem with PHP 4.3.1 (installed with SuSE 8.2). ...
|
|||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
Hi all,
I have encountered a "tricky" problem with PHP 4.3.1 (installed with SuSE 8.2). I don't know if it is a bug or not. Maybe is just me missing something. What I'd like to do is to pass a reference of "base_class" instance to the constructor of "second_class" (so that the newly created "second_class" instance can call methods from the "base_class" instance. It seems that if "base_class" constructor directly calls its method "create()" (that is responsible of creating the "second_class" instance, passing _$this_ as constructor argument) the second_class gets a "copy" of "base_class" instance and not the real thing. To test it, I have added an array ($arr) in the base_class and set a value into it. If "second_class" really have a reference to the "real" base_class instance, it should be able to print its contents, but this just doesn't work. Please, notice that if in the following code you remove the line "$this->create()" in the base_class constructor and add the commented line in the main body, everything works fine. What I am really missing? Please, help! Ciao, Fabio ---- CODE STARTS HERE ------------------------------------------ <?php class base_class { var $arr; var $class; function base_class () { $this->arr = array (); $this->class = false; // it seems to create another "instance" of base_class $this->create (); // this line does not work } function set ( $val ) { $this->arr [] = $val; } function create () { $this->class = new second_class ( $this ); } function test () { $this->class->dump (); } } class second_class { function second_class ( & $main_class ) { $this->main_class = & $main_class; } function dump () { print_r ( $this->main_class->arr ); } } $b = new base_class (); // $b->create (); // This line works as expected $b->set ( "ciao" ); $b->test (); print "<br />"; print_r ( $b->arr ); ?> ---- END CODE --------------------------------------------- |