php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #18684 Parser error when trying to create a new class instance in a static definition
Submitted: 2002-08-01 10:53 UTC Modified: 2002-09-09 10:15 UTC
Votes:1
Avg. Score:3.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: michiwalter at gmx dot de Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 4.2.1, 4.3.0-dev OS: Windows 2000, Tru64
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: michiwalter at gmx dot de
New email:
PHP Version: OS:

 

 [2002-08-01 10:53 UTC] michiwalter at gmx dot de
Summary:

Parser error when trying to create a new class instance in a static definition.

Error reproducable on:
- Windows 2000/IIS/PHP 4.2.1 (CGI)
- Windows 2000/Apache 1.3.24/PHP 4.2.0
- Linux deathrow 2.4.9-34/Apache 1.3.26/PHP 4.2.2

Test script:
<?php
  class Test
  {
  };
  
  function test()
  {
    static $var=new Test();
  }
?>

Error message:
Parse error: parse error, unexpected T_NEW in __FILE__ on line __LINE__

Known workarounds:
...
function test()
{
  static $var=NULL;
  if(NULL===$var)
    $var=new Test();
  return $var;
}
...

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2002-08-01 14:05 UTC] nohn@php.net
Verified this "bug" with 4.3.0-dev on Compaq Tru64 though I can't see any sense in what you're trying to do.
 [2002-08-01 14:36 UTC] michiwalter at gmx dot de
Well I am under the impression that in the definition

static $var=<value>;

<value> should be assigned to $var only the first call...so what I want to do is to use that for implementing a singleton, like that:

class Class
{
  //...
  function &getSingleton()
  {
    static $instance=new Class();
    return $instance;
  }
  // ...
}

(similar to Class& getSingleton() { static Class instance; return instance; } in C++, and yeah, I know that that ain't thread safe;)

Anything wrong with that?
 [2002-09-09 10:15 UTC] stas@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

Static vars as of now can be initialized only by static (meaning, constant) expressions. So, use your workaround. 
 
PHP Copyright © 2001-2026 The PHP Group
All rights reserved.
Last updated: Wed Oct 07 16:00:02 2026 UTC