Call a PHP static method with a variable class name and namespaces

I am trying to call a static method for a class with names from another class with the same namespace. But another class name is contained in the variable:

<?php namespace MyApp\Api; use \Eloquent; class Product extends Eloquent { public static function find($id) { //.... } public static function details($id) { $product = self::find($id); if($product) { $type = $product->type; // 'Book' $product = $type::find($product->id); return $product; } } } 

Here is the Book class:

 <?php namespace MyApp\Api; use \Eloquent; class Book extends Eloquent { public static function find($id) { //.... } } 

My type variable contains a valid class name here Book . This class is in the same folder and uses the same namespace. This code returns a Class 'Book' not found error. I tried several options (from the questions I found) using a backslash or the call_user_func function, but nothing call_user_func . Does anyone know what happened?

+7
source share
2 answers

When using a variable to reference your class, you need to use the full name. Try it...

 $type = __NAMESPACE__ . '\\' . $product->type; $product = $type::find($product->id); 
+11
source

@Phil pointed out the right solution.

For a fuller point of view, I clarify that a full name is required when accessing static methods or attributes from the global namespace.

When accessing dynamic methods or attributes (I mean instance properties) without qualifying the name, PHP automatically searches for the property inside the current namespace.

In my opinion, this asymmetry is not useful, since the ability to refer to the properties of the external namespace is the same for either static or dynamic properties.

(Valid on PHP 7.2.0 at the time of writing).

0
source

Source: https://habr.com/ru/post/1245466/


All Articles