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
 [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-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 26 15:01:56 2024 UTC