php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #74633 object as class name
Submitted: 2017-05-22 17:36 UTC Modified: 2017-05-23 06:58 UTC
From: d dot albano at gmail dot com Assigned:
Status: Not a bug Package: Documentation problem
PHP Version: 7.1.5 OS: Mac OS X 10.12.5
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: d dot albano at gmail dot com
New email:
PHP Version: OS:

 

 [2017-05-22 17:36 UTC] d dot albano at gmail dot com
Description:
------------
It is possible to use an object as class name in new

Test script:
---------------
<?php
class Foo { };
$foo = new Foo();
$bar = new $foo();
var_dump([$foo, $bar]);

Expected result:
----------------
Error, cannot use $foo as class name

Actual result:
--------------
array(2) {
  [0]=>
  object(Foo)#1 (0) {
  }
  [1]=>
  object(Foo)#2 (0) {
  }
}


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-05-22 17:40 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2017-05-22 17:40 UTC] requinix@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.new
 [2017-05-22 22:31 UTC] d dot albano at gmail dot com
The documentation states that it is possible to pass to new a variable containing the name of the class to instantiate (a string in the example) but the code I am passing an object. 
Trying to echo the object results in an error and defining the to string magic method doesn't affect the behavior of the new keyword.
 [2017-05-23 06:58 UTC] requinix@php.net
Did you read example #5?

PHP 5.3.0 introduced a couple of new ways to create instances of an object:

$obj1 = new Test();
$obj2 = new $obj1;
var_dump($obj1 !== $obj2);
 
PHP Copyright © 2001-2020 The PHP Group
All rights reserved.
Last updated: Thu Nov 26 04:01:23 2020 UTC