php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #64847 It appears that traits may define static member variables
Submitted: 2013-05-15 18:49 UTC Modified: 2013-10-13 17:40 UTC
Votes:1
Avg. Score:4.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:0 (0.0%)
Same OS:1 (100.0%)
From: mhorowitz at etsy dot com Assigned: krakjoe (profile)
Status: Closed Package: Documentation problem
PHP Version: 5.4.15 OS: linux
Private report: No CVE-ID: None
 [2013-05-15 18:49 UTC] mhorowitz at etsy dot com
Description:
------------
Try it -- put a static variable in a trait declaration, then access that variable 
in code defined in the trait and/or defined in the "exhibiting" class.  It works 
just fine.

I spoke with Rasmus; we both believe this is fine behavior and that the 
documentation (quoted below) should be changed to make it clear that one can, in 
fact, declare a static variable within the trait definition.

Quote from: http://php.net/manual/en/language.oop5.traits.php

"Static variables can be referred to in trait methods, but cannot be defined by 
the trait."

Test script:
---------------
<?php
// So, the following works and, for my purposes, is really, really useful.

trait TTrait {
    protected static $instance = 'hello there';

    public function publicFn() {
        echo self::$instance . "\n";
	echo "publicFn\n";
    }
}

class Foo {
    use TTrait;

    public function tryMe() {
        echo "From Foo: "; $this->publicFn();
        echo "In tryMe -- instance is: " . self::$instance . "\n";
    }
}

$f = new Foo();

$f->tryMe();


Expected result:
----------------
As noted, please adjust the doc to reflect that static variable declarations are 
actually allowed.  Currently, name collisions are handled as is done for non-
static properties (i.e. E_STRICT error, as per the doc for properties).

In the future, it might be nice if the renaming clause would work for static 
variables too.



Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2013-10-13 17:40 UTC] krakjoe@php.net
Automatic comment from SVN on behalf of krakjoe
Revision: http://svn.php.net/viewvc/?view=revision&amp;revision=331806
Log: #64847 correction
 [2013-10-13 17:40 UTC] krakjoe@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: krakjoe
 [2013-10-13 17:40 UTC] krakjoe@php.net
This bug has been fixed in the documentation's XML sources. Since the
online and downloadable versions of the documentation need some time
to get updated, we would like to ask you to be a bit patient.

Thank you for the report, and for helping us make our documentation better.


 
PHP Copyright © 2001-2026 The PHP Group
All rights reserved.
Last updated: Wed Oct 07 19:00:01 2026 UTC