php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #62254 Allow explicit call of a trait methods
Submitted: 2012-06-07 18:44 UTC Modified: 2021-08-16 12:19 UTC
Votes:6
Avg. Score:3.8 ± 0.9
Reproduced:5 of 5 (100.0%)
Same Version:1 (20.0%)
Same OS:1 (20.0%)
From: jachym dot tousek at gmail dot com Assigned: cmb (profile)
Status: Wont fix Package: Class/Object related
PHP Version: 5.4.3 OS: All
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2012-06-07 18:44 UTC] jachym dot tousek at gmail dot com
Description:
------------
Hi,

I have a little feature request. I'd like to call a method from a used trait explicitly, even though it was redefined in the class itself. It actually does work now, but it causes an error (see actual result bellow) which it shouldn't in my opinion.

This should probably only work for traits used by the class itself, not for traits used by parent classes nor traits used by traits.

I know about the "as" keyword but that's not what I want in this case. See my actual goal at the end od the test script (in comment) for details.

Test script:
---------------
<?php

trait A {

	public function method() {
		echo 'A';
	}

}

trait B {

	public function method() {
		echo 'B';
	}

}

class C {
	use A, B;

	public function method() {
		A::method();
		B::method();
		echo 'C';
	}

}

$obj = new C;
$obj->method();

/*
My actual goal is something like this:

class D {
	use A, B;

	public function method() {
		$method = __FUNCTION__;
		foreach (class_uses($this) as $trait) {
			if (method_exists($trait, $method)) {
				$trait::$method();
			}
		}
	}

}

$obj = new D;
$obj->method();
*/

Expected result:
----------------
ABC

Actual result:
--------------
Strict Standards: Non-static method A::method() should not be called statically, assuming $this from incompatible context in E:\localhost\www\traits.php on line 23
A
Strict Standards: Non-static method B::method() should not be called statically, assuming $this from incompatible context in E:\localhost\www\traits.php on line 24
BC

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2021-08-16 12:19 UTC] cmb@php.net
-Status: Open +Status: Wont fix -Assigned To: +Assigned To: cmb
 [2021-08-16 12:19 UTC] cmb@php.net
Even calling static trait methods is deprecated as of PHP
8.1.0[1], so allowing to call non-static methods would not make
sense.  Use composition instead.

[1] <https://github.com/php/php-src/blob/php-8.1.0beta2/UPGRADING#L354-L356>
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Tue Mar 19 04:01:31 2024 UTC