Access constant without self::? - php

I'd like to use some constants with a function, but it is laborious and ugly to refer to them with self:: every time. Is there a way to just access them by name without specifying scope?
class My_Class {
const CLASS_CONSTANT = 'test value';
private function my_function(){
// Is there a way to access this without self::
$a = self::CLASS_CONSTANT;
}
}

One possible (but clunky) way to achieve this, is using the define() function. The only problem with this approach is that it defines the variable in a global scope.
Here is how to use it:
define ('text', 'Foo Bar?!');
echo text;
Will return: Foo Bar?!
So to integrate this into a class you can do the following:
class My_Class{
function __construct(){
define ('CLASS_CONSTANT', 'test value');
}
private function display(){
echo CLASS_CONSTANT;
}
}
$example = new My_Class();
$example->display();
This outputs: test value
Do note that define() is a function, and as such requires to be executed inside of a function block, or outside of the class. It can not be easily declared at the top of a class like normal class constants.

You can use ReflectionClass to get all the constants of a class
$oClass = new \ReflectionClass(My_Class::class);
$constants = $oClass->getConstants();
foreach ($constants as $name => $value) {
//to work
}
For more visit: http://php.net/manual/en/reflectionclass.getconstants.php
Hope it helps!

Related

How to access the constant in the class? [duplicate]

I'm trying to access a class constant in one of my classes:
const MY_CONST = "value";
If I have a variable which holds the name of this constant like this:
$myVar = "MY_CONST";
Can I access the value of MY_CONST somehow?
self::$myVar
does not work obviously because it is for static properties.
Variable variables does not work either.
There are two ways to do this: using the constant function or using reflection.
Constant Function
The constant function works with constants declared through define as well as class constants:
class A
{
const MY_CONST = 'myval';
static function test()
{
$c = 'MY_CONST';
return constant('self::'. $c);
}
}
echo A::test(); // output: myval
Reflection Class
A second, more laborious way, would be through reflection:
$ref = new ReflectionClass('A');
$constName = 'MY_CONST';
echo $ref->getConstant($constName); // output: myval
There is no syntax for that, but you can use an explicit lookup:
print constant("classname::$myConst");
I believe it also works with self::.
Can I access the value of MY_CONST somehow?
self::MY_CONST
If you want to access is dynamically, you can use the reflection API Docs:
$myvar = 'MY_CONST';
$class = new ReflectionClass(self);
$const = $class->getConstant($myVar);
The benefit with the reflection API can be that you can get all constants at once (getConstants).
If you dislike the reflection API because you don't wanna use it, an alternative is the constant function (Demo):
$myvar = 'MY_CONST';
class foo {const MY_CONST = 'bar';}
define('self', 'foo');
echo constant(self.'::'.$myvar);
Just a note for Reflection: the constructor for ReflectionClass must receive the full path of the class for its parameter.
This means that just setting the string 'A' as a constructor parameter may not work in some cases.
To avoid this problem, when using ReflectionClass you will be better if you do this:
$classA = new A();
$name_classA = get_class($classA);
$ref = new ReflectionClass(get_class($name_classA));
$constName = 'MY_CONST';
echo $ref->getConstant($constName);
Function get_class will give you the full path of a class whenever you are in the code. Missing the full path may result in a "Class not found" PHP error.
have you tried
$myVar = MY_CONST or $myVar = $MY_CONST

How to access static constants with a string variable [duplicate]

I'm trying to access a class constant in one of my classes:
const MY_CONST = "value";
If I have a variable which holds the name of this constant like this:
$myVar = "MY_CONST";
Can I access the value of MY_CONST somehow?
self::$myVar
does not work obviously because it is for static properties.
Variable variables does not work either.
There are two ways to do this: using the constant function or using reflection.
Constant Function
The constant function works with constants declared through define as well as class constants:
class A
{
const MY_CONST = 'myval';
static function test()
{
$c = 'MY_CONST';
return constant('self::'. $c);
}
}
echo A::test(); // output: myval
Reflection Class
A second, more laborious way, would be through reflection:
$ref = new ReflectionClass('A');
$constName = 'MY_CONST';
echo $ref->getConstant($constName); // output: myval
There is no syntax for that, but you can use an explicit lookup:
print constant("classname::$myConst");
I believe it also works with self::.
Can I access the value of MY_CONST somehow?
self::MY_CONST
If you want to access is dynamically, you can use the reflection API Docs:
$myvar = 'MY_CONST';
$class = new ReflectionClass(self);
$const = $class->getConstant($myVar);
The benefit with the reflection API can be that you can get all constants at once (getConstants).
If you dislike the reflection API because you don't wanna use it, an alternative is the constant function (Demo):
$myvar = 'MY_CONST';
class foo {const MY_CONST = 'bar';}
define('self', 'foo');
echo constant(self.'::'.$myvar);
Just a note for Reflection: the constructor for ReflectionClass must receive the full path of the class for its parameter.
This means that just setting the string 'A' as a constructor parameter may not work in some cases.
To avoid this problem, when using ReflectionClass you will be better if you do this:
$classA = new A();
$name_classA = get_class($classA);
$ref = new ReflectionClass(get_class($name_classA));
$constName = 'MY_CONST';
echo $ref->getConstant($constName);
Function get_class will give you the full path of a class whenever you are in the code. Missing the full path may result in a "Class not found" PHP error.
have you tried
$myVar = MY_CONST or $myVar = $MY_CONST

Accessing a class constant using a simple variable which contains the name of the constant

I'm trying to access a class constant in one of my classes:
const MY_CONST = "value";
If I have a variable which holds the name of this constant like this:
$myVar = "MY_CONST";
Can I access the value of MY_CONST somehow?
self::$myVar
does not work obviously because it is for static properties.
Variable variables does not work either.
There are two ways to do this: using the constant function or using reflection.
Constant Function
The constant function works with constants declared through define as well as class constants:
class A
{
const MY_CONST = 'myval';
static function test()
{
$c = 'MY_CONST';
return constant('self::'. $c);
}
}
echo A::test(); // output: myval
Reflection Class
A second, more laborious way, would be through reflection:
$ref = new ReflectionClass('A');
$constName = 'MY_CONST';
echo $ref->getConstant($constName); // output: myval
There is no syntax for that, but you can use an explicit lookup:
print constant("classname::$myConst");
I believe it also works with self::.
Can I access the value of MY_CONST somehow?
self::MY_CONST
If you want to access is dynamically, you can use the reflection API Docs:
$myvar = 'MY_CONST';
$class = new ReflectionClass(self);
$const = $class->getConstant($myVar);
The benefit with the reflection API can be that you can get all constants at once (getConstants).
If you dislike the reflection API because you don't wanna use it, an alternative is the constant function (Demo):
$myvar = 'MY_CONST';
class foo {const MY_CONST = 'bar';}
define('self', 'foo');
echo constant(self.'::'.$myvar);
Just a note for Reflection: the constructor for ReflectionClass must receive the full path of the class for its parameter.
This means that just setting the string 'A' as a constructor parameter may not work in some cases.
To avoid this problem, when using ReflectionClass you will be better if you do this:
$classA = new A();
$name_classA = get_class($classA);
$ref = new ReflectionClass(get_class($name_classA));
$constName = 'MY_CONST';
echo $ref->getConstant($constName);
Function get_class will give you the full path of a class whenever you are in the code. Missing the full path may result in a "Class not found" PHP error.
have you tried
$myVar = MY_CONST or $myVar = $MY_CONST

PHP access external $var from within a class function

In PHP, how do you use an external $var for use within a function in a class? For example, say $some_external_var sets to true and you have something like
class myclass {
bla ....
bla ....
function myfunction() {
if (isset($some_external_var)) do something ...
}
}
$some_external_var =true;
$obj = new myclass();
$obj->myfunction();
Thanks
You'll need to use the global keyword inside your function, to make your external variable visible to that function.
For instance :
$my_var_2 = 'glop';
function test_2()
{
global $my_var_2;
var_dump($my_var_2); // string 'glop' (length=4)
}
test_2();
You could also use the $GLOBALS array, which is always visible, even inside functions.
But it is generally not considered a good practice to use global variables: your classes should not depend on some kind of external stuff that might or might not be there !
A better way would be to pass the variables you need as parameters, either to the methods themselves, or to the constructor of the class...
Global $some_external_var;
function myfunction() {
Global $some_external_var;
if (!empty($some_external_var)) do something ...
}
}
But because Global automatically sets it, check if it isn't empty.
that's bad software design. In order for a class to function, it needs to be provided with data. So, pass that external var into your class, otherwise you're creating unnecessary dependencies.
Why don't you just pass this variable during __construct() and make what the object does during construction conditional on the truth value of that variable?
Use Setters and Getters or maybe a centralized config like:
function config()
{
static $data;
if(!isset($data))
{
$data = new stdClass();
}
return $data;
}
class myClass
{
public function myFunction()
{
echo "config()->myConfigVar: " . config()->myConfigVar;
}
}
and the use it:
config()->myConfigVar = "Hello world";
$myClass = new myClass();
$myClass->myFunction();
http://www.evanbot.com/article/universally-accessible-data-php/24

instantiate a class from a variable in PHP?

I know this question sounds rather vague so I will make it more clear with an example:
$var = 'bar';
$bar = new {$var}Class('var for __construct()'); //$bar = new barClass('var for __construct()');
This is what I want to do. How would you do it? I could off course use eval() like this:
$var = 'bar';
eval('$bar = new '.$var.'Class(\'var for __construct()\');');
But I'd rather stay away from eval(). Is there any way to do this without eval()?
Put the classname into a variable first:
$classname=$var.'Class';
$bar=new $classname("xyz");
This is often the sort of thing you'll see wrapped up in a Factory pattern.
See Namespaces and dynamic language features for further details.
If You Use Namespaces
In my own findings, I think it's good to mention that you (as far as I can tell) must declare the full namespace path of a class.
MyClass.php
namespace com\company\lib;
class MyClass {
}
index.php
namespace com\company\lib;
//Works fine
$i = new MyClass();
$cname = 'MyClass';
//Errors
//$i = new $cname;
//Works fine
$cname = "com\\company\\lib\\".$cname;
$i = new $cname;
How to pass dynamic constructor parameters too
If you want to pass dynamic constructor parameters to the class, you can use this code:
$reflectionClass = new ReflectionClass($className);
$module = $reflectionClass->newInstanceArgs($arrayOfConstructorParameters);
More information on dynamic classes and parameters
PHP >= 5.6
As of PHP 5.6 you can simplify this even more by using Argument Unpacking:
// The "..." is part of the language and indicates an argument array to unpack.
$module = new $className(...$arrayOfConstructorParameters);
Thanks to DisgruntledGoat for pointing that out.
class Test {
public function yo() {
return 'yoes';
}
}
$var = 'Test';
$obj = new $var();
echo $obj->yo(); //yoes
I would recommend the call_user_func() or call_user_func_arrayphp methods.
You can check them out here (call_user_func_array , call_user_func).
example
class Foo {
static public function test() {
print "Hello world!\n";
}
}
call_user_func('Foo::test');//FOO is the class, test is the method both separated by ::
//or
call_user_func(array('Foo', 'test'));//alternatively you can pass the class and method as an array
If you have arguments you are passing to the method , then use the call_user_func_array() function.
example.
class foo {
function bar($arg, $arg2) {
echo __METHOD__, " got $arg and $arg2\n";
}
}
// Call the $foo->bar() method with 2 arguments
call_user_func_array(array("foo", "bar"), array("three", "four"));
//or
//FOO is the class, bar is the method both separated by ::
call_user_func_array("foo::bar"), array("three", "four"));

Categories