Access static object property through variable name - php

I know its possible to access an object property/method using a variable as its name
ex.:
$propName = 'something';
$something = $object->$propName;
Is it possible to do the same w/ constants or static properties?
I've tried:
$constName = 'MY_CONST';
MyCLass::{$constName};
and
$obj::{$constName};
But nothing seems to work and I couldn't find it anywhere.

Use: Class::$$constName, this is similar to normal variable variables.
Demo:
<?php
class MyClass {
public static $var = 'A';
}
$name = 'var';
echo MyClass::$$name; // echoes 'A'
Constants can be access with the constant function:
constant('MyClass::'.$constantName)

This works for me:
<?php
class Test {
public static $nombre = "pepe";
public function __construct() {
return self;
}
}
$varName = "nombre";
echo Test::${$varName};

You can use the constant function:
constant('bar::'. $const);
constant("$obj::". $const); //note the double quote

Related

PHP - Make 'new' of a Class and Arguments set in a string

I've a Class and Arguments set in a variable like this:
$myVar = '\Api\MyClass(\DateTimeInterface::RFC3339_EXTENDED)';
I need to make a new of this variable.
I tried multiple solutions and at the end the new of the Class was solved but I cannot pass the argument.
My code is:
<?php
$myVar = '\Api\MyClass(\DateTimeInterface::RFC3339_EXTENDED)';
$className = substr($myVar, 0, strpos($myVar, "(")); // $className will be: \Api\MyClass
if (class_exists($className)) {
preg_match('/\((.*?)\)/', $myVar, $classArguments); $classArguments will be: \DateTimeInterface::RFC3339_EXTENDED
$obj = new $className($classArguments[1]); // it doesn't work
}
the problem is that $classArguments[1] is passed as string to my class. Below the difference:
// It works
$p = \DateTimeInterface::RFC3339_EXTENDED;
var_dump($p);
// and return
string(15) "Y-m-d\TH:i:s.vP"
// It doesn't work
$p = "\DateTimeInterface::RFC3339_EXTENDED";
var_dump($p);
// return
string(36) "\DateTimeInterface::RFC3339_EXTENDED"
can you help me?
Thank you.
New can only be used to create an instance. Make your constructor expecting that date format as default, so you are not required to pass it.
class MyClass {
public function __construct(string $dateFormat = DateTimeInterface::RFC3339_EXTENDED)
{
}
}
$var = 'MyClass';
$instance = new $var;
$p = "\DateTimeInterface::RFC3339_EXTENDED";
will not work, because that is now a string and not the constants value.
You also can pass something like so
class MyClass {
public function __construct(string $something = '')
{
echo $something;
}
}
$var = 'MyClass';
$text = 'Hello world';
$instance = new $var($text);
Hello world
If you need the complete string to be parsed try eval(), but not recommended.
$var = 'new MyClass("hello world");';
$instance = eval($var);
Hello world
or, but not recommended.
$var = 'MyClass("hello world")';
$instance = eval("new {$var};");
Hello world
You can use the constant function to get the value of a constant.
A simple example class that just outputs the parameter value when initialized.
class MyClass
{
function __construct($arg) {
echo "$arg\n";
}
}
new MyClass('anything'); // outputs "anything"
This is just a helper that gets the class name and argument string from a string like your $myVar.
function parseClassAndArgument(string $str): array {
preg_match('/(.*)\((.*)\)/', $str, $matches);
[, $className, $argument] = $matches;
return [$className, $argument];
}
This helper allows you to pass either a string value or a name of a constant, and guesses which one it is based on whether there is a :: in the string name. You can replace this with just the constant($argument) part if you know $myVar will always contain a constant name.
function parseArgValue(string $argument): string {
return strpos($argument, '::') ? constant($argument) : $argument;
}
This recognizes that $argument refers to a constant and outputs Y-m-d\TH:i:s.vP
$myVar = 'MyClass(\DateTimeInterface::RFC3339_EXTENDED)';
[$className, $argument] = parseClassAndArgument($myVar);
new $className(parseArgValue($argument));
This outputs the string foo as is.
$myVar = 'MyClass(foo)';
[$className, $argument] = parseClassAndArgument($myVar);
new $className(parseArgValue($argument));
This is a simplified example that only handles one parameter for the class constructor, but I hope it helps to get you along!

outer variables define inside a class

how do you define a variable in a class? seems like global only works inside the function.
<?php
$a = '20';
$b = '10';
class test {
global $a; $b;
function add() {
echo $a;
}
}
$answer = new test();
$answer->add();
?php>
i tried this one (use global inside a class but gets error instead)
also, how can you define multiple variables in just 1 line of code instead of defining it each.
To define a class property (or variable), you would do like so:
class Foo {
private $myVar = 'my var'; // define a class property
public function add() {
echo $this->myVar;
}
}
How about passing the data in via the constructor?
Code: (Demo)
$a_outside = '20';
$b_outside = '10';
class test {
public $a_inside;
public $b_inside;
public function __construct($a_passed_in, $b_passed_in)
{
$this->a_inside = $a_passed_in;
$this->b_inside = $b_passed_in;
}
public function add()
{
echo $this->a_inside + $this->b_inside;
}
}
$answer = new test($a_outside, $b_outside);
$answer->add(); // output: 30
Pass the variable to the class via arguments in the constructor call.
Define the values as variables in the class within construct call.
Access the variables within the add() method.

Call variable from a function that's inside a class?

I just created my first PHP class, but I'm very new to this and now I don't know how to call a variable inside a function that I created.
For example:
class Example
{
public function testFunction() {
$var1 = "Test";
$var2 = "Hello";
}
}
And then, for example, echo $var1.
I know that I can call the function through this:
$something = new Example();
$something->testFunction();
But how can I call one of those variables inside the function?
I also know that if the variable was outside the function, it would be:
$something = new Example();
echo $something->var1;
I could use a return, but that way I would end with just one variable, and I have multiple variables inside that function.
I hope that you can help me.
Variables inside functions aren't available outside them. The function needs to return the variable.
i.e.
function getName(){
return "helion3";
}
echo $myClass->getName();
If you need more than one, return an array:
return array("name1","name2");
To access variables from outside class functions like that, you need to set the variables as properties of the class:
class Example {
public $var1 = '';
private $var3 = ''; // private properties etc are not available outside the class
public function testFunction() {
$this->var1 = 'Test';
$var2 = 'Test2';
$this->var3 = 'Test3';
}
}
$something = new Example();
echo $something->var1; // Test
echo $something->var2; // can't do this at all (it's not an object property)
echo $something->var3; // can't do this, it's private!
Of course, you can return whatever you like from the function itself...
public function testFunction() {
$this->var1 = 'Test';
$var2 = 'Test2';
$this->var3 = 'Test3';
return array($this->var1, $var2, $this->var3);
}
You can return private properties and locally scoped variables...
list($var1, $var2, $var3) = $something->testFunction(); // all there!
Variables declared inside your function are only accessible within the function body.
If your function needs to return more than one value, you either a) return a new object, or b) return an array:
return [$var1, $var2];
And in the calling code:
list($a, $b) = $something->testFunction();

Using a define (or a class constant) to call a variable method?

Is it possible to :
define('DEFAULT_METHOD', 'defaultMethod');
class Foo
{
public function defaultMethod() { }
}
$foo = new Foo();
$foo->DEFAULT_METHOD();
Or do I have to :
$method = DEFAULT_METHOD;
$foo->$method();
And what about a class constant instead of a define ?
If you use a variable or constant as the method name, you have to put it into curly brackets:
$foo->{DEFAULT_METHOD}();
The same technique works for variables, including static class attributes:
class Foo {
public static $DEFAULT_METHOD = 'defaultMethod';
public function defaultMethod() { echo "Cool!\n"; }
}
$foo = new Foo();
$foo->{FOO::$DEFAULT_METHOD}();
In fact, practically any expression that results in a valid method name could be used:
$foo->{'default'.'Method'}();
You could set it to a variable first as in your example :)
Example: http://codepad.org/69W4dYP1
<?php
define('DEFAULT_METHOD', 'defaultMethod');
class Foo {
public function defaultMethod() { echo 'yay!'; }
}
$foo = new Foo();
$method = DEFAULT_METHOD;
$foo->$method();
?>

Get a static property of an instance

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;

Categories