I have a question regarding "dynamic" class initialising, let me explain what I mean:
$class = 'User';
$user = new $class();
//...is the same as doing
$user = new User();
So... that's not the problem, but I am having some trouble doing the same while calling a static variable from a class, for example:
$class = 'User';
print $class::$name;
Which gives out the following error:
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in
Off course I have tested doing print User::$name; and that works. So class works.
Why is this and is there a way around it?
Follow up question:
Also is there any valid reasons to not use this "dynamic" way in creating classes?
This code works good on PHP 5.4.3:
<?php
class A {
public static $var = "Hello";
}
print(A::$var);
$className = "A";
print($className::$var);
?>
This is the answer from the question I linked in the comments:
You can use reflection to do this. Create a ReflectionClass
object given the classname, and then use the getStaticPropertyValue
method to get the static variable value.
class Demo
{
public static $foo = 42;
}
$class = new ReflectionClass('Demo');
$value=$class->getStaticPropertyValue('foo');
var_dump($value);
If you don't have PHP version of 5.3 and above, and you don't want to use reflection (which in my opinion is an overkill - unless you want to access multiple static properties) you can define getter function and call it via call_user_func():
class A {
public static $var = "Hello";
public static function getVar() {
return self::$var;
}
}
$className = "A";
echo call_user_func(array($className, 'getVar'));
Related
I have trouble accessing a constant of a class via the object operator(->).
I have these 2 classes:
class withConstant {
const MY_CONSTANT = 5;
}
class usingConstant {
public $class = null;
function __construct() {
$this->class = new withConstant();
}
}
When I do this:
$myClass = new usingConstant();
echo $myClass->class::MY_CONSTANT;
I get an error Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM). However, I can get around it with this:
$myClass = new usingConstant();
$myClass = &$myClass->class;
echo $myClass::MY_CONSTANT;
I prefer to access the constant without assigning the member variable to another variable first.
This is the closest I can come to what you're actually after achieving unfortunately:
echo constant(get_class($myClass->class).'::MY_CONSTANT');
Note that this is incredibly inefficient, since it looks up the class to determine it's name, then looks it up again to reference the constant.
You can make a getter function in withConstant and call that.
class withConstant {
const MY_CONSTANT = 5;
function getConstant(){
return self::MY_CONSTANT;
}
}
Then you can call that function:
$myClass = new usingConstant();
echo $myClass->class->getConstant();
In PHP sometimes it would be nice if I could define a function or a class with a variable name like
$myfunctionname="test";
function $myfunctionname(){
//...
}
so it would create the function test()
or with classes too like:
$foo = bar;
class $foo {
// lots of complicated stuff
// ...
}
but this doesen't work. like this it would give parse errors!
Is there a solution to this?
(I know, this is not good practise, but just as a workaround, it would be handy)
EDIT: My actual problem:
I have a framework with a migration process where every migration step is in a separate php include file in a folder.
Each file contains only one migration class that contains the name of the include file.
Because the class has to have that certain name, I would like to create the name of the class to a generic name that is created by the filename constant __FILE__
Yes, you can, but I dont want you to.
$classname = "test";
eval("class {$classname}{ public function hello(){ echo \"hello!\"; } }");
$evil_class = new $classname();
$evil_class->hello(); // echo's "hello!"
now, if you don't mind me I'm going for a shower.
You can use a factory pattern:
class poly_Factory {
public function __construct() {
$class = 'poly';
return new $class();
}
}
If that is anything you want to get to.
http://net.tutsplus.com/tutorials/php/understanding-and-applying-polymorphism-in-php/
Scroll down to step 4, last part...
I know you did not ask for that, but what can your question be good for else?
No. This code throws a parse error on line 3 because of the $:
$foo = 'bar';
class $foo {
function hello() {
echo "World";
}
}
$mybar = new bar();
$mybar->hello();
Result:
Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING on line 3
And as Jan Dvorak pointed out in the comments: even if you figure out a way to do this, don't do this.
If you want to create a value object you can just use the stdClass builtin type.
$object = new stdClass;
$object->someValue = "Hello World";
echo $object->someValue;
See it in Action
If you want to assign methods then you have to use the magic __call function, here is how I would do it.
class AnonObject{
private $properties = array();
private $methods = array();
public function __get($property){
return array_key_exists($property, $this->properties)?$this->properties[$property]:null;
}
public function __set($property, $value){
if (!is_string($value) && is_callable($value)){
if ($value instanceof \Closure){
// bind the closure to this object's instance and static context
$this->methods[$property] = $value->bindTo($this,get_class($this));
} else {
// invokable objects
$this->methods[$property] = $value;
}
} else {
$this->properties[$property] = $value;
}
}
public function __call($method, $args){
if (array_key_exists($method, $this->methods)){
call_user_func_array($this->methods[$method], $args);
} else {
throw new RuntimeException("Method ".$method." does not exist on object");
}
}
}
See it In Action
Note, as stated by several other people this is bad practice. If the goal of this exercise is to compose the behavior of an instance of an object at runtime a more maintainable solution would be to use the Strategy Pattern
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;
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
From the string name of a class, can I get a static variable?
Somewhere in a parent class, I need to find the value of a static variable of one of the possible child classes, determined by the current instance.
I wrote:
$class = get_class($this);
$value = isset($class::$foo['bar']) ? $class::$foo['bar'] : 5;
In this example, the subclass whose name is in $class has a public static $foo.
I know using $class::$foo['bar'] is not a very beautiful piece of code, but it gets the job done on PHP 5.3.4.
In PHP 5.2.6 though, I am getting a syntax error:
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting ',' or ')'
Is there an alternative way that would work on PHP 5.2.4+ that would get the same thing done?
EDIT: Reflection is better.
You can try the get_class_vars method. No access to PHP 5.2.6, but this works in 5.2.11...
class Test {
public static $foo;
function __construct() {
echo("...Constructing...<br/>");
Test::$foo = array();
Test::$foo['bar'] = 42;
}
function __toString() {
return "Test";
}
}
$className = 'Test';
$class = new $className();
$vars = get_class_vars($className);
echo($vars['foo']['bar'] . "<br/>");
Output:
...Constructing...
42
The reason that this does not work in PHP 5.2, is because before PHP 5.3 you are not allowed to use variables in the classname. So, if possible use eval for this.
eval('$result = ' . $c . '::$foo[\'bar\'];');
echo $result;
Otherwise, you're forced to use a function in the child class to receive the value. For example:
class MyParent {
public function __construct() {
$var = $this->_getVariable();
echo $var['bar'];
}
}
class MyChild extends MyParent {
static $var = array('bar' => 'foo');
protected function _getVariable() {
return self::$var;
}
}
new MyChild();
class Bar1 {
static $var = array('index' => 'value');
}
class Bar2 extends Bar1 {
}
class Foo extends Bar2 {
static $var = array('index' => 'value in Foo');
public function __construct() {
echo parent::$var['index'];
}
}
$foo = new Foo();
will output 'value', but not 'value in Foo'
Hope, that's what you are looking for.
You can get class static/call static method in the class you are working in using self key word or for parent class using parent. You can get that error on php 5.2.6 because of changes in get_class function in PHP 5.3.0
I am trying to access a static method, but using a variable as the class name. Is this possible? I seem to be having issues with it. I want to be able to do something like this:
class foo {
public static function bar() {
echo 'test';
}
}
$variable_class_name = 'foo';
$variable_class_name::bar();
And I want to be able to do similar using static variables as well.
That syntax is only supported in PHP 5.3 and later. Previous versions don't understand that syntax, hence your parse error (T_PAAMAYIM_NEKUDOTAYIM refers to the :: operator).
In previous versions you can try call_user_func(), passing it an array containing the class name and its method name:
$variable_class_name = 'foo';
call_user_func(array($variable_class_name, 'bar'));
You can use reflection for PHP 5.1 and above:
class foo {
public static $bar = 'foobar';
}
$class = 'foo';
$reflector = new ReflectionClass($class);
echo $reflector->getStaticPropertyValue('bar');
> foobar