php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #2675 Misbehavior of object initializers
Submitted: 1999-11-05 20:06 UTC Modified: 1999-11-06 11:47 UTC
From: zerodiv at zerodivide dot net Assigned:
Status: Closed Package: Other
PHP Version: 3.0.12 OS: all tested
Private report: No CVE-ID: None
 [1999-11-05 20:06 UTC] zerodiv at zerodivide dot net
<?php
class Foo {
	var $type;
	Function Foo() {
		$this->type = 'Foo';
	}
}

class Bar {
	var $type;
	Function Bar() {
		$this->type = 'Bar';
	}
}

// This will work
$foo = new Foo();
echo( 'I am foo : ' . $this->type );

// This will not
$bar = new Bar();
echo( 'I should be foo also : ' . $this->type );

?>

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [1999-11-05 23:38 UTC] zerodiv at zerodivide dot net
<?php
                                         class Foo {
                                                 var $type;
                                                 Function Foo() {
                                                         $this->type = 'Foo';
                                                 }
                                         }

                                         class Bar {
                                                 var $type;
                                                 Function Bar() {
                                                         $this->type = 'Bar';
				return new Foo();
                                                 }
                                         }

                                         // This will work
                                         $foo = new Foo();
                                         echo( 'I am foo : ' . $foo->type );

                                         // This will not
                                         $bar = new Bar();
                                         echo( 'I should be foo also : ' . $bar->type );

                                         ?>
 [1999-11-06 11:47 UTC] andi at cvs dot php dot net
This is not a bug. You are misusing constructors. What the new operator does is similar to C++. It first allocates memory for the object and then calls the objects constructor. The constructor does not have a return value and returning something from it is pointless. When you're calling new Bar(); you're telling PHP you want a new object of type Bar and not foo. Maybe what you want is inheritence?
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Dec 26 10:01:29 2024 UTC