php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #60214 can't instantiate using class constant
Submitted: 2011-11-03 17:34 UTC Modified: 2011-11-03 20:53 UTC
Votes:1
Avg. Score:3.0 ± 0.0
Reproduced:0 of 0 (0.0%)
From: gabriel at totoliciu dot ro Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.3SVN-2011-11-03 (snap) OS: 2.6.34-gentoo-r6 GNU/Linux
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: gabriel at totoliciu dot ro
New email:
PHP Version: OS:

 

 [2011-11-03 17:34 UTC] gabriel at totoliciu dot ro
Description:
------------
I wanted to write something like this inside a method.
DEFAULT_CLASS is a string containing a name of an existing class.
The problem is that there is no way to instantiate an object using a class 
constant by using "new self::CLASS_CONSTANT";

This will generate a syntax error.

I know that the workaround is to store the value of the class constant into a 
variable, but couldn't this be improved somehow?

Test script:
---------------
<?php
class default_class {
    function do_nothing() {
    }
}

class TheParent {

const DEFAULT_CLASS="default_class";

    public function init() {
        $c=new self::DEFAULT_CLASS;
    }

}

Expected result:
----------------
I would expect to have an object instantiated with the class stored in the 
DEFAULT_CLASS constant.

Actual result:
--------------
Produces a syntax error:

syntax error, unexpected T_STRING, expecting T_VARIABLE or '$' in 
/some_path/test.php on line 14


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2011-11-03 17:36 UTC] gabriel at totoliciu dot ro
I forgot to mention that you have to run Parent::init();
 [2011-11-03 20:27 UTC] anon at anon dot anon
As a simple workaround you can do:
$c = self::DEFAULT_CLASS;
$c = new $c();
 [2011-11-03 20:53 UTC] felipe@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

At least currently it's not even intended to work. Use the workaround instead.
 [2011-11-03 20:53 UTC] felipe@php.net
-Status: Open +Status: Bogus
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Mon Jul 14 07:01:32 2025 UTC