php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #63646 Trait method names matching classes that use said trait treated as constructors
Submitted: 2012-11-29 09:48 UTC Modified: 2012-12-02 14:05 UTC
From: phpbugs at catchall dot drarok dot com Assigned:
Status: Wont fix Package: Scripting Engine problem
PHP Version: master-Git-2012-11-29 (Git) OS: OS X 10.8
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2012-11-29 09:48 UTC] phpbugs at catchall dot drarok dot com
Description:
------------
If you use a Trait which has a method name matching your class name, it is used as 
an old-style constructor in the case where the using class doesn't define a 
constructor.

If you *do* define a constructor, you receive the error "Fatal error: Hello has 
colliding constructor definitions coming from traits".

Test script:
---------------
<?php
trait HelloWorld {
	public function hello() { echo 'Hello, World!', PHP_EOL; }
	static public function world() { echo 'World; Hello!', PHP_EOL; }
}

class Hello { use HelloWorld; }
class World { use HelloWorld; }

new Hello();
new World();

/*
 * # php example.php
 * Hello, World!
 * World; Hello!
 */

Expected result:
----------------
Given that Traits cannot be used in legacy code, I'd expect the method name to be 
irrelevant to constructor behaviour.

Actual result:
--------------
Method names that match the class name are used as a constructor.

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2012-12-01 11:31 UTC] laruence@php.net
-Status: Open +Status: Wont fix
 [2012-12-01 11:31 UTC] laruence@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

the method name same as class name is considered as constructor as of PHP 5.4 

although we encourage use __construct instead of that. but it should also be 
compatible
 [2012-12-01 12:19 UTC] nikic@php.net
@laruence: On the other hand, if you are using a namespaced class old-style constructors aren't used either. So the same might also be done with traits.
 [2012-12-02 14:05 UTC] phpbugs at catchall dot drarok dot com
@nikic: precisely what I was thinking!
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 19 20:01:29 2024 UTC