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.
Related
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.
I'd like to pass (any type, not only PHP's primitives) Type as a function parameter. More like a C++'s template. Is it possible in PHP? imaginary code:
function foo(T a)
{
$output = new T();
//do something.
}
I tried pass the type name as string and then use settype() to the the variable to that type but settype() work only with PHP's primitives types. My goal is actually pass a class type as parameter.
If you want to instantiate something like the above, how about passing the classname as a string and then instantiating it!
function foo($obj_string)
{
$object = new $obj_string();
//do stuff with $object
}
I see that you already accepted an answer, but from the original post, it shows passing an object variable in the function. For those viewing this that need to do it that way, instead of being able to pass the name of the class as a string, you can do it this way:
class Blah
{
public $x = 123;
}
function Foo($b) {
$class = get_class($b);
$object = new $class();
var_dump($object);
}
$aa = new Blah();
Foo($aa);
I realize this is a bit old but I'll leave an answer anyway just in case it's helpful.
If I am going to pass an object as a parameter to another object, it's going to be after I have instantiated the object argument and adjusted the properties to my needs. The following is an example of how I would go about it. I'm using this on PHP 7.4.x and haven't tested on PHP 8.x yet.
Class Blah is the object that will be passed to an instance of Class Bleep after the property $x within the Class Blah object has been changed from 123 to 456.
<?php
class Blah {
public $x = 123;
function __construct() {}
function set_x($x) {
$this->x = $x;
}
function get_x() {
return $this->x;
}
}
class Bleep {
public $object;
function __construct($object) {
$this->object = $object;
}
function get_object_x() {
return $this->object->get_x();
}
}
// Example in use.
$obj_bla = new Blah();
print '<p>On instantiation of <u>$obj_bla</u> as a <strong>Blah</strong> object, $x = '.$obj_bla->get_x().'</p>';
$obj_bla->set_x(456);
print '<p>After using the method <i>set_x()</i> on <u>$obj_bla</u>, $x = '.$obj_bla->get_x().'</p>';
$obj_bleep = new Bleep($obj_bla);
print '<p>Instantiate <u>$obj_bleep</u> as a new <strong>Bleep</strong> object and pass it the instance of <u>$obj_bla</u> then use the <i>get_object_x()</i> method on <u>$obj_bleep</u> to get the value of x from the object that was passed = '.$obj_bleep->get_object_x().'</p>'
?>
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.
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.
If I have an instance in PHP, what's the easiest way to get to a static property ('class variable') of that instance ?
This
$classvars=get_class_vars(get_class($thing));
$property=$classvars['property'];
Sound really overdone. I would expect
$thing::property
or
$thing->property
EDIT: this is an old question. There are more obvious ways to do this in newer
PHP, search below.
You need to lookup the class name first:
$class = get_class($thing);
$class::$property
$property must be defined as static and public of course.
From inside a class instance you can simply use self::...
class Person {
public static $name = 'Joe';
public function iam() {
echo 'My name is ' . self::$name;
}
}
$me = new Person();
$me->iam(); // displays "My name is Joe"
If you'd rather not
$class = get_class($instance);
$var = $class::$staticvar;
because you find its two lines too long, you have other options available:
1. Write a getter
<?php
class C {
static $staticvar = "STATIC";
function getTheStaticVar() {
return self::$staticvar;
}
}
$instance = new C();
echo $instance->getTheStaticVar();
Simple and elegant, but you'd have to write a getter for every static variable you're accessing.
2. Write a universal static-getter
<?php
class C {
static $staticvar = "STATIC";
function getStatic($staticname) {
return self::$$staticname;
}
}
$instance = new C();
echo $instance->getStatic('staticvar');
This will let you access any static, though it's still a bit long-winded.
3. Write a magic method
class C {
static $staticvar = "STATIC";
function __get($staticname) {
return self::$$staticname;
}
}
$instance = new C();
echo $instance->staticvar;
This one allows you instanced access to any static variable as if it were a local variable of the object, but it may be considered an unholy abomination.
classname::property;
I think that's it.
You access them using the double colon (or the T_PAAMAYIM_NEKUDOTAYIM token if you prefer)
class X {
public static $var = 13;
}
echo X::$var;
Variable variables are supported here, too:
$class = 'X';
echo $class::$var;
You should understand what the static property means. Static property or method is not for the objects. They are directly used by the class.
you can access them by
Class_name::static_property_name
These days, there is a pretty simple, clean way to do this.
<?php
namespace Foo;
class Bar
{
public static $baz=1;
//...
public function __toString()
{
return self::class;
}
}
echo Bar::$baz; // returns 1
$bar = new Bar();
echo $bar::$baz; // returns 1
You can also do this with a property in PHP 7.
<?php
namespace Foo;
class Bar
{
public static $baz=1;
public $class=self::class;
//...
}
$bar = new Bar();
echo $bar->class::$baz; // returns 1
class testClass {
public static $property = "property value";
public static $property2 = "property value 2";
}
echo testClass::$property;
echo testClass::property2;