Difference between $object->lol and $object->$lol - php

I am having a confusion between this two kinds of code and want to know, what is the difference between them:
$object->$lol
// and
$object->lol

$object->lol will points to some property as defined on the object class:
class SomeClass {
public $lol = 'some value';
}
$object = new SomeClass();
echo $object->lol; //will yield 'some value'
And $object->$lol will point to some property as defined on the object class, but will access the correct property based on the value for $lol:
class SomeClass {
public $lol = 'some value';
public $random = 'random value';
}
$lol = 'random';
$object = new SomeClass();
echo $object->lol; //will yield 'some value'
echo $object->$lol; //will yield 'random value'

$object->lol access a instance variable named lol on the $object object.
$object->$lol access a instance variable that has the name contained in the $lol variable. It is also accessd on the $object object.

AFAIK, it works the same as the following:
$var = "var2";
$var2 = "hello world";
echo $$var; // This returns "hello world"
So, I assume that $object->$lol gets you the variable with the name of your $lol variable.
Here is some more info about this...

First one is like
$lol = 'foo';
$object->{$lol} == $object->foo;
Second one is regular property access.

I will explain you this,look this code:
<?php
$var1->"hello";
$var2->$var1;
?>
If we do a print or an echo $var1 will show "hello" but in $var2 we will see "hello" again because $var1 and $var2 are the same.
In the second code:
<?php
$var1->"hello";
$var2->"var1";
?>
Now we print $vare1 and it'll show "hello" but $var2 will show "var1".I hope this help you to solve your problem.

Related

Is it okay to use dynamic variables to access class properties in PHP?

Today, I realised that I could use variables to access property names in a class, i.e. instead of using $object->foo I can set a string variable as $propname="foo" and then access the property with $object->$propname.
Is this method okay to use, or is it possible that I will get unexpected behaviours/errors that I haven't thought of?
Example code:
<?php
class MyClass {
public $a = "Hello world!";
public $b = "Bye bye!";
}
$obj = new MyClass();
$property = "a";
echo $obj->$property; // Hello world!
$property = "b";
echo $obj->$property; // Bye bye!
?>
As a note: I want to use this method in my code where I have classes with many properties and I whish to be able to return diff-responses between objects, like compare_properties($propertyname, $obj1, $obj2)

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!

php - How to access objects using string?

I know accessing object's properties dynamically using string e.g.
$obj->{$string};
But what about objects themselves?
Like I have string
$obj = '$model->property';
How to use this?
For example in if statement, to have something like
if($model->property) but by using this string?
Tried if({$obj}), if(${$obj})... nothing works.
I don't know if it even possible, but maybe?
I've set up a small test case...
class A {
public $b = 5;
}
$test = new A();
$var = "test";
echo ${$var}->b;
I think this last line is what your after.
Update:
If you want the object and the property, then the nearest I could get is to use...
class A {
public $b = 5;
}
$test = new A();
$var = "test->b";
list($var, $property) = explode("->", $var);
echo ${$var}->$property;

Variable variables concept confusion

Hey guys am a newbie in PHP. I have seen some code like:
<?php
class foo {
var $bar = 'I am bar.';
var $arr = array('I am A.', 'I am B.', 'I am C.');
var $r = 'some';
}
$foo = new foo();
$arr = 'arr';
echo $foo->$arr[1];
?>
It returns some. Why it is returning some. echo $foo->$arr[1] means it should output I am B. But instead it outputs some; why?
When you access a property of a class, you don't use $ before the property. If you do, it will evaluate that portion first, to figure out what property to access.
echo $foo->$arr[1];
$arr is 'arr', so when you access it as an array, it will grab the letter at whatever index you specify.
$arr[1] is "r";
$foo->r = 'some';
If you access the object property without the $:
echo $foo->arr[1];
it will output I am B.
As a side note, if you DO want to use variable-variables, and it's an array, you should really use parenthesis.
$foo->$arr[1];
is ambiguous as to whether you mean
($foo->$arr)[1];
or
$foo->($arr[1]);
Try,
<?php
class foo {
public $bar = 'I am bar.';
public $arr = array('I am A.', 'I am B.', 'I am C.');
public $r = 'some';
}
$foo = new foo();
echo $foo->arr[1];
?>
To access object variable have to use $foo->var_name;

Why does this not make a difference between property and variable?

class someclass
{
public $foo = 'abcd';
public function __construct($data)
{
$this->foo = $data;
}
public function doSomething()
{
$user = $_POST['username'];
echo $foo = $_POST['foo']; // This output correct value
var_dump($foo); // This Output NULL
$somethingelse = $_POST['foo'];
var_dump($somethingelse); // Output as expected
}
}
If i change my variable name or property name from $foo to something else in do in doSomething() it runs fine.
Why do I need to keep the property name and variable name different here?
Why does $foo is NULL when one of the property name is $foo?
You need to use $this->foo to get and set the classes property
change this
echo $foo = $_POST['foo'];
to
echo $this->foo = $_POST['foo'];
var_dump($this->foo);
When accessing class variables you need to use the $this-> prefix.
Change your code to
echo $this->foo = $_POST['foo'];
var_dump($this->foo);
It is correct and it works fine. I ran your code and it always gives me the same. There's no problem you have property $foo and $foo variable in one or multiple functions. It always give me the same answer.
If $_POST['foo']=test then echo $foo = $_POST['foo']; returns "test", $foo returns "test" and $somethingelse returns "test";

Categories