Use string as object name in PHP - php

I want to use a string as an object name in PHP.
For example:
$name = 'utils';
$obj = new $name();
$utils->test();
So I want to be able to call the object by the name of a string (since I don't know the class names beforehand).
How would I be able to do this?

Try the following:
$name = 'utils';
$$name = new $name();
See Namespaces and dynamic language features ¶ for more information

Class Foo {
function bar(){
return 'text';
}
}
$name = 'Foo';
$obj = new $name();
echo $obj->bar();

Related

how to access constant variable of a class using string in phppresentation [duplicate]

I would like to be able to do something like this:
class ThingIDs
{
const Something = 1;
const AnotherThing = 2;
}
$thing = 'Something';
$id = ThingIDs::$thing;
This doesn't work. Is there a straightforward way of doing something equivalent? Note that I'm stuck with the class; it's in a library I can't rewrite. I'm writing code that takes arguments on the command line, and I would really like it to take symbolic names instead of id numbers.
Use the constant() function:
$id = constant("ThingIDs::$thing");
Use Reflection
$r = new ReflectionClass('ThingIDs');
$id = $r->getConstant($thing);
If you are using namespaces, you should include the namespace with the class.
echo constant('My\Application\ThingClass::ThingConstant');
Helper function
You can use a function like this:
function class_constant($class, $constant)
{
if ( ! is_string($class)) {
$class = get_class($class);
}
return constant($class . '::' . $constant);
}
It takes two arguments:
Class name or object instance
Class constant name
If an object instance is passed, its class name is inferred. If you use PHP 7, you can use ::class to pass appropriate class name without having to think about namespaces.
Examples
class MyClass
{
const MY_CONSTANT = 'value';
}
class_constant('MyClass', 'MY_CONSTANT'); # 'value'
class_constant(MyClass::class, 'MY_CONSTANT'); # 'value' (PHP 7 only)
$myInstance = new MyClass;
class_constant($myInstance, 'MY_CONSTANT'); # 'value'
<?php
class Dude {
const TEST = 'howdy';
}
function symbol_to_value($symbol, $class){
$refl = new ReflectionClass($class);
$enum = $refl->getConstants();
return isset($enum[$symbol])?$enum[$symbol]:false;
}
// print 'howdy'
echo symbol_to_value('TEST', 'Dude');
If you have a reference to the class itself then you can do the following:
if (defined(get_class($course). '::COURSES_PER_INSTANCE')) {
// class constant is defined
}
My problem was similiar to this subject. When you have the object, but not the class name, you could use:
$class_name = get_class($class_object);
$class_const = 'My_Constant';
$constant_value = constant($class_name.'::'.$class_const);
I know I'm a bit late, but I hope this can help anyway.
Based on Phil's answer, I created a default enumerator class that can be extended.
class DefaultEnum
{
static public function getConstantText(string $constant)
{
try {
// Get child class name that called this method
$child_class = get_called_class();
$reflection = new ReflectionClass($child_class);
$const = $reflection->getConstant($constant);
return $const;
} catch (\ReflectionException $e) {
// ...
}
}
}
class CustomEnum extends DefaultEnum
{
const something = 'abcd';
const something2 = 'ABCD';
}
You can call this method like this
CustomEnum::getConstantText('something');
It will return 'abcd'.
The function get_called_class() is a function that returns the class name that called this method and it works specifically for static methods.
In this case $child_class value will be CustomEnum::class. ReflectionClass accepts strings and object as parameter.

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:
controller_$var;
but I assume that's a syntax error.
How can I do this?
function __construct()
{
$this->_section = self::path();
new Controller_{$this->_section};
}
It's a hideous hack, but:
php > class foo { function x_1() { echo 'success'; } };
php > $x = new foo;
php > $one = 1;
php > $x->{"x_$one"}();
^^^^^^^^^^^^
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.
echo "controller_{$var}";
Try this (based on your code in the OP):
function __construct()
{
$this->_section = self::path();
$controller_name = "Controller_{$this->_section}";
$controller = new $controller_name;
}
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);
try this:
$name = "controller_$var";
echo $this->$name;
just to add on the previous answers, if you're trying to declare new classes with variable names but all the construction parameters are the same and you are treating the instanced object all alike maybe you don't need different classes but just different instances of the same.

how to store constructed variable name

I wold like to get the following variable name:
class ClassA
{
public $my_name_is = "";
function __construct($tag,$cont = null)
{
$this->my_name_is = ???;
}
}
$OBJ = new ClassA();
echo($OBJ->my_name_is);
This should output
OBJ
Is it possible?
I make tag HTML generator and the id of the tag should be the object name so I must not write it twice:
$input_pwd = new tag("td>input TYPE=PASSWORD.box_lg#input_pwd"); //old way
$input_pwd = new tag("td>input TYPE=PASSWORD.box_lg"); //upgraded way
should generate:
<td><input TYPE=PASSWORD ID='input_pwd' CLASS='box_lg'></td>
No, it's not. An object doesn't know the names of variables that refer to it.
"Needing" this is usually a design flaw.
You can use the magic constant __CLASS__ for retrieving the name of the current class, but there is no way for a class to get the name of the variable which stores the class. You may want to extend your class and still use __CLASS__:
class OBJ extends ClassA {
public function getName() {
return __CLASS__;
}
}
$OBJ = new OBJ();
$OBJ->getName();
See also: http://php.net/manual/en/language.constants.predefined.php
If you simply want to ensure that each reference to the object has a unique ID, you can do that with a static variable.
class ClassA {
public function getUniqueName() {
static $count = 0;
++$count;
return __CLASS__ . '.' . $count;
}
}
$OBJ = new ClassA();
echo($OBJ->getUniqueName();
Every time that method is called, it will give you a different result. If you call it only once on each variable, you should be fine.

PHP analog to C++ member pointers?

Does PHP have something similar to C++ member pointers? I want to use a member of a PHP object, whose name (the member's, not the object's) I only know at runtime. For example:
$object = new stdClass();
$object->NewMember = "value";
$member = 'NewMember';
// I don't know whether this is valid PHP,
// but you get what I'm trying to do.
echo $object->$member;
<?php
class Test
{
public $foo = 'bar';
}
$var = 'foo';
$test = new Test();
echo $test->$var;
Edit: after your update, yes, that will work.
You can use variables in member calls.
$methodName = 'some_method';
$myObj->$methodName($param);
Not sure if this will work for what you want.
In the following code I'm setting the $memberToGet at runtime:
class Person
{
public $foo = 'default-foo';
public $bar = 'default-bar';
}
$p = new Person();
$memberToGet = 'foo';
print "The Person's $memberToGet is [" . $p->$memberToGet . "]\n";
$memberToGet = 'bar';
print "The Person's $memberToGet is [" . $p->$memberToGet . "]\n";
No, PHP doesn't support (member) pointers. However you could use Reflection API.
class MyClass {
public function doSth($arg1, $arg2) { ... }
public static function doSthElse($arg1) { ... }
}
$ref = new ReflectionMethod('MyClass', 'doSth');
$ref->invokeArgs(new MyClass(), array('arg1', 'arg2'));
$ref = new ReflectionMethod('MyClass', 'doSthElse');
$ref->invokeArgs(null, array('arg1'));
As you can see in other answers you could also write:
class MyClass { ... }
$method = 'doSth';
$obj = new MyClass();
$obj->$method('arg1', 'arg2');
But I really don't recommend that way. It's tricky, obscure and much harder to debug and maintain.
By passing $this as a variable by reference, you can access members of that class.

Instantiate a new class with the value of a string

This might be a very stupid question :P But I found this really interessting:
class SomeClass{
var $var = "this is some text";
function echoVar($name){
echo $this->{$name};
}
}
$class = new SomeClass()
$class->echoVar("var") // will echo "this is some text"
Can I do somethign similar, can I take the value of a string and instantiate a new class with that name? If not, any "almost" solutions?
Thanks
Yes. You can dynamically instantiate classes in PHP. Like this:
$className = 'SomeClass';
$myInstance = new $className();
If your string 'dave' is in $name, you can use it with $$name
$name = 'dave';
$$name = new SomeClass();
$dave->echoVar('var');

Categories