Use string as class name php

instanceof equivalent for a string-represented classname

I’m looking for a functionality, in the example below called «theFunctionILookFor», that will make the code work.

$myClassName = "someName"; $parentOrInterfaceName = "someParent"; if (theFunctionILookFor($myClassName))

Edit: I try to avoid instantiating the class just to perform this check. I would like to be able to pass 2 string parameters to the checking function

7 Answers 7

Looks like this is my answer: is_subclass_of

It can accept both parameters as strings

Note that is_subclass_of check for children only and won’t match if given class is the same as second parameter: class MyClass <> var_dump(is_subclass_of(‘MyClass’, ‘MyClass’)); var_dump(is_subclass_of(new MyClass(), ‘MyClass’)); Result: boolean false boolean false

It worths noting that is_subclass_of triggers autoloader in case the classname does not exist. It doesn’t if the third parameter is false , but then you can’t provide a string as first parameter.

This answer is slightly incorrect. The correct answer to match logical equivalent of instanceof is is_a() with true passed as third parameter as pointed in the comments. The is_subclass_of() does not match self unlike instanceof and is_a() .

Try is_subclass_of() . It can accept both parameters as strings. http://php.net/manual/en/function.is-subclass-of.php

Using the Reflection API, you can construct a ReflectionClass object using the name of the class as well as an object.

get_parent_class

(PHP 4, PHP 5, PHP 7)
get_parent_class — Retrieves the parent class name for object or class

Description

string get_parent_class ([ mixed $object ] ) 

Retrieves the parent class name for object or class.

This is an old thread, but still for future reference, you can use the functions is_a and is_subclass_of to accomplish this in a more efficient way. No need to instantiate anything, you can just pass your string like:

if (is_subclass_of($myObject, 'SomeClass')) // is_a(. ) echo "yes, \$myObject is a subclass of SomeClass\n"; else echo "no, \$myObject is not a subclass of SomeClass\n"; 
http://www.php.net/manual/en/function.is-a.php http://www.php.net/manual/en/function.is-subclass-of.php 

Keep in mind that is_a() and is_subclass_of() are not equivalent. A class is not a subclass of itself.

Maybe it’s old question, but problem still is actual, here, below, the best solution I’ve found

class ProductAttributeCaster < public function cast(mixed $value): mixed < if ($value instanceof ($this->castTo())) < // do stuff >return $value; > function castTo(): string < return ProductAttribute::class; >> 

I think that instanceof is a lot faster and more clear to read.

Читайте также:  Нет файла template php

instanceof does not work on strings, because it can be used as a «identifier» for a class:

 $temp = 'tester'; $object = new sub(); var_dump($object instanceof $temp); //prints "true" on php 5.3.8 class tester<> class sub extends \tester

Also, it works on interfaces — you just need a variable to contain the absolute class name (including namespace, if you want to be 100% sure).

OP clearly asked about the situation where a) there is not object, b) the object shouldn’t/musn’t be instantiated. This doesn’t answer the question as it currently stands.

Also note that you cannot blindly instantiate an object. For example, if the class to be tested is RAII interface to SQL database, the constructor would need to create a database connection and you should definitely not do that blindly. Use is_a() instead with third parameter set to true . As the original question already mentions instanceof trying to suggest it as an answer to the question provides no value, hence -1.

Источник

It is possible to convert from a string to class name in PHP

I want to convert from a string to Class name in PHP as below script. But i got errors Class name must be a valid object or a string it may be error because tables still a string.

$table = Teller::select('*')->where('user_id','=', $this->user_id)->first(); $modelName = trim($table->tables,'"'); $loan = $modelName::select('*')->where('id','=', $id)->get(); 

yes I just copy and pass to DB and I try to initial to $Model_name value like this too $ModelName = «ClassName». Notes: ClassName is $table->tables value in DB

2 Answers 2

Consider this Simple Scenario:

 > $b = SomeClass::getSomeData(); //DUMPS '12 some value another value' TO THE OUTPUT STREAM. var_dump($b); $strClassName = "SomeClass"; //STILL DUMPS '12 some value another value' TO THE OUTPUT STREAM. var_dump(call_user_func($strClassName. "::getSomeData")); 

Extending this Knowledge to your Unique Case, You might want to do something like:

 where('user_id','=', $this->user_id)->first(); $modelName = trim($table->tables,'"'); $implicitCall = call_user_func($modelName. "::select", '*'); $implicitCall = call_user_func($modelName. "::where", array('id', '=', $id)); $loan = call_user_func($modelName. "::get"); ?> 

Optionally; You may even take this a little further. Since we know that you are using Fluent Setters; it is clear that the First implicit call will return an instance of the Class so we could do something like so:

 where('user_id','=', $this->user_id)->first(); $modelName = trim($table->tables,'"'); // THIS SHOULD RETURN AN INSTANCE OF THE CLASS IN QUESTION: THE MODEL CLASS $implicitCall = call_user_func($modelName. "::select", '*'); // DO YOU DOUBT IT? WELL, DOUBT IS THE BEGINNING OF ALL KNOWLEDGE. // I DOUBT IT TOO; SO LET'S CONFIRM OUR DOUBTS var_dump($implicitCall); // EXPECTED TO DUMP THE CLASS IN QUESTION. // NOW WE CAN JUST USE THE $implicitCall VARIABLE AS IF IT WAS AN INSTANCE OF THE MODEL CLASS LIKE SO: $loan = $implicitCall->where('id','=', $id)->get(); ?> 

I hope this answers helps and works for you though. 😉

Читайте также:  Java ввод вывод консоль

Источник

Convert string to safe name for class

I have a dynamic menu that I need to convert into background images using CSS classes. I would like to convert the label into a safe class name for the css. An example being: — Convert string: ‘Products & Sunflowers’ — Into a string that contains only a-z and 1-9. The above would be converted into a validate string that can be used as a class name eg: ‘products_sunflowers’

Not sure what you are asking here. Could you spend more time defining the problem and give code examples of what you’ve tried?

5 Answers 5

preg_replace('/\W+/','',strtolower(strip_tags($className))); 

It will strip all but letters, convert to lower-case and remove all html tags.

Have you tried preg_replace ?

This will return ‘ProductsSunflowers’ for your above example.

Technically if this is going to be truly CSS safe you need to also ensure that the classname doesn’t start with a number. I’d just go with preg_replace(‘/\W+/’, », $className) to strip all but letters.

Yes, you’re right, but if the goal is simply to create a CSS safe class name this would achieve that, it may not be the best or most exhaustive set of options for anything valid, but it’s probably one of the simplest. I’m sure the regex could be made more complete if hyphens really matter. You should probably add this comment to the accepted answer too.

BEM-style clean_class php solution

Shamelessly interpolated from Drupal 7’s drupal_clean_css_identifier() and Drupal 10 Html::cleanCssIdentifier() functions.

/** * Convert any random string into a classname following conventions. * * - preserve valid characters, numbers and unicode alphabet * - preserve already-formatted BEM-style classnames * - convert to lowercase * * @see http://getbem.com/ */ function clean_class($identifier) < // Convert or strip certain special characters, by convention. $filter = [ ' ' =>'-', '__' => '__', // preserve BEM-style double-underscores '_' => '-', // otherwise, convert single underscore to dash '/' => '-', '[' => '-', ']' => '', ]; $identifier = strtr($identifier, $filter); // Valid characters in a CSS identifier are: // - the hyphen (U+002D) // - a-z (U+0030 - U+0039) // - A-Z (U+0041 - U+005A) // - the underscore (U+005F) // - 0-9 (U+0061 - U+007A) // - ISO 10646 characters U+00A1 and higher // We strip out any character not in the above list. $identifier = preg_replace('/[^\\x\\x-\\x\\x-\\x\\x\\x-\\x\\x-\\x]/u', '', $identifier); // Convert everything to lower case. return strtolower($identifier); > 

Источник

Читайте также:  Parse nested xml in java

Use variable’s string into class names or other

I want to use variables inside class names. For example, let’s set a variable named $var to «index2». Now I want to print index2 inside a class name like this: controller_index2 , but instead of doing it manually, I can just print the var name there like this:

 function __construct() < $this->_section = self::path(); new Controller__section>; > 

5 Answers 5

php > class foo < function x_1() < echo 'success'; >>; php > $x = new foo; php > $one = 1; php > $x->(); ^^^^^^^^^^^^ success 

Instead of trying to build a method name on-the-fly as a string, an array of methods may be more suitable. Then you just use your variables as the array’s key.

Echo it as a string in double quotes.

Try this (based on your code in the OP):

function __construct() < $this->_section = self::path(); $controller_name = "Controller__section>"; $controller = new $controller_name; > 

I get one error now Parse error: syntax error, unexpected ‘

You can do this. follow this syntax

function __construct() < $this->_section = self::path(); $classname = "Controller_".$this->_section; $instance = new $classname(); > 

Another way to create an object from a string definition is to use ReflectionClass

$classname = "Controller_".$this->_section; $reflector = new ReflectionClass($classname); 

and if your class name has no constructor arguments

$obj = $reflector->newInstance(); 

of if you need to pass arguments to the constructor you can use either

$obj = $reflector->newInstance($arg1, $arg2); 

or if you have your arguments in an array

$obj = $reflector->newInstanceArgs($argArray); 

Источник

How to tell phpDoc a string is a class name?

I often give objects static methods and properties that do not require the object to be initialized. For example:

class SomeObject < public function __construct($object_id) < $this->loadProperties($object_id); > public static function getSomeStaticString() < return "some static string"; >> 

Now we subclass these objects and have some sort of controller that returns an object class string under certain circumstances where the object should not yet be initialized. For example:

class SomeObjectController < public function getSomeObjectWithTheseProperties(array $properties) < if($properties[0] === "somevalue") < if($properties[1] === "someothervalue") < return SomeSubclassObject::class; >return SomeObject::class; > return NULL; > > 

At times I might want to call the static function SomeObject::getSomeStaticString() without actually initializing the object (because that would involve an unneeded database fetch). For instance:

$controller = new SomeObjectController; $properties = array("somevalue", "someothervalue"); $object_class = $controller->getSomeObjectWithTheseProperties($properties); echo $object_class::getSomeStaticString(); 

Question: can I somehow tell PhpStorm, preferably through phpDoc, that $object_class is a class string of a subclass of SomeObject ? If I tell my IDE it’s a string, it will notify me getSomeStaticString() is an invalid method. On the other hand, if I tell my IDE it’s an instance of SomeObject, it thinks I can access regular non-static methods and properties, which I can’t.

Источник

Оцените статью