Is there a way to access a member of an object, by using its name as a string?
When I declare an array...
$array = array();
$array['description_en']="hello";
$array['description_fr']="bonjour";
then I access a member like this:
$lang="en"; //just to show my purpose. it will be dynamic
$description = $array['description_'.$lang];
Can I do the same thing for objects?
For example:
$obj->description_en="hello";
$obj->description_fr="bonjour";
How can I access $obj->description_.$lang ?
class test
{
public $description_en = 'english';
}
$obj = new test();
$lang = 'en';
echo $obj->{"description_".$lang}; // echo's "english"
You can see more examples of variable variables here.
You can use this syntax:
<?php
class MyClass {
public $varA = 11;
public $varB = 22;
public $varC = 33;
}
$myObj = new MyClass();
echo $myObj->{"varA"} . "<br>";
echo $myObj->{"varB"} . "<br>";
echo $myObj->{"varC"} . "<br>";
This way, you can access object variables as if they were entries in an associative array.
Related
I have the following a PHP object with the following properties:
Object:
-Advanced
--Data
To access it in PHP I would have to do the following:
$object->Advanced->Data
Now I want to define a string which has a syntax like this:
$string = "Advanced->Data";
How do I proceed from here to be able to use:
$object->$string = "Something";
So that in the end
$object->Advanced->Data = "Something";
I couldn't figure out using eval or $object->{$string}
If I try to use $object->$string
PHP creates a new property called "Advanced->Data", basically not interpreting the -> Operator.
Though it is a hack, try this, it should work for your case
$arr = array();
$arr['Advanced']['Data'] = 'something';
$string = json_decode(json_encode($arr), 0);
echo $string->Advanced->Data;
Though it is a hack, this can also fetch your desire
$string = &$object->Advanced->Data;
$string = "here we go";
var_dump($object->Advanced->Data);
Probably eval() is not best solution, but it can be useful in your case:
class obj2 {
public $Data = 'test string';
}
class obj1 {
public $Advanced;
public function __construct() {
$this->Advanced = new obj2();
}
}
$test = new obj1();
$string1 = "\$test->Advanced->Data = 'new string';";
$string2 = "\$result = \$test->Advanced->Data;";
eval($string1);
eval($string2);
echo $result . PHP_EOL;
Output will be "new string".
Once try this,
$string = "Advanced->Data";
$arr = explode("->",$string);
$temp = $object->{$arr[0]}->$arr[1];
But this is specific condition. Let me know your requirement if this is not the answer.
I have created a class called Functions which stores 3 public variables ($var1, $var2, $var3). I have a for loop that creates an object of that class, that updates the variables of the class and then add that object to an array. However, when I try and access the array, I get an error "Undefined property: Functions::$InsertTextHere".
The strange thing is, it doesn't play the error if I check the array at [$i], only if I check anywhere else in the array that was created in a previous iteration. For example, the echo within the for loop will not spark the error however the echos outside the for loop will.
I am sorry if this is hard to understand, please let me know if it is.
class Functions{
public $var1 = "";
public $var2 = "";
public $var3 = "";
}
$file <---- Puts out about 14 different lines
$fileContentArray = array();
for($i = 0; count($file) > $i; $i++){
$var1 = "randomstuff1: " . $i;
$var2 = "randomstuff2: " . $i;
$var3 = "randomstuff3: " . $i;
$temp = new Functions();
$temp->$var1 = $var1;
$temp->$var2 = $var2;
$temp->$var3 = $var3;
$fileContentArray[] = $temp;
echo $fileContentArray[$i]->$var3; <--- Doesn't Give Errors
}
echo $fileContentArray[0]->$var3; <--- Gives Errors
echo $fileContentArray[1]->$var3; <--- Gives Errors
echo $fileContentArray[13]->$var3; <--- Doesn't give error, final entry in array
You shouldn't use "$" on the object properties (variable) unless you want variable variables
class Functions{
public $var1 = "";
public $var2 = "";
public $var3 = "";
}
$file <---- Puts out about 14 different lines
$fileContentArray = array();
for($i = 0; count($file) > $i; $i++){
$var1 = "randomstuff1: " . $i;
$var2 = "randomstuff2: " . $i;
$var3 = "randomstuff3: " . $i;
$temp = new Functions();
$temp->var1 = $var1;
$temp->var2 = $var2;
$temp->var3 = $var3;
$fileContentArray[] = $temp;
echo $fileContentArray[$i]->$var3; <--- Doesn't Give Errors
}
echo $fileContentArray[0]->var3; <--- Gives Errors
echo $fileContentArray[1]->var3; <--- Gives Errors
echo $fileContentArray[13]->var3; <--- Doesn't give error, final entry in array
Edit: please see this as referrences
http://www.php.net//manual/en/language.variables.variable.php
http://www.php.net//manual/en/sdo.sample.getset.php
I'm wondering if this was possible and I could not find a way to do it so I ask. How can I get the name of the variable where in a instance of a class is present.
Pseudo code:
class test{
public $my_var_name = '';
function __construct(){
//the object says: Humm I am wondering what's the variable name I am stored in?
$this->my_var_name = get_varname_of_current_object();
}
}
$instance1 = new test();
$instance2 = new test();
$boeh = new test();
echo $instance1->my_var_name . ' ';
echo $instance2->my_var_name . ' ';
echo $boeh->my_var_name . ' ';
The output would be like:
instance1 instance2 boeh
Why! Well I just wanna know its possible.
I have no idea why, but here you go.
<?php
class Foo {
public function getAssignedVariable() {
$hash = function($object) {
return spl_object_hash($object);
};
$self = $hash($this);
foreach ($GLOBALS as $key => $value) {
if ($value instanceof Foo && $self == $hash($value)) {
return $key;
}
}
}
}
$a = new Foo;
$b = new Foo;
echo '$' . $a->getAssignedVariable(), PHP_EOL; // $a
echo '$' . $b->getAssignedVariable(), PHP_EOL; // $b
I created this code trying to answer for How to get name of a initializer variable inside a class in PHP
But it is already closed and referenced to this question,
just another variant easy to read, and I hope I didn't break any basic concept oh php development:
class Example
{
public function someMethod()
{
$vars = $GLOBALS;
$vname = FALSE;
$ref = &$this;
foreach($vars as $key => $val) {
if( ($val) === ($ref)) {
$vname = $key;
break;
}
}
return $vname;
}
}
$abc= new Example;
$def= new Example;
echo $abc->someMethod();
echo $def->someMethod();
I can't find a good reason to do that.
Anyways, one way you can do (but again it has no use as far as i can imagine) this is by passing the instance name as a constructor's parameter, like this:
$my_instance = new test("my_instance");
I'm confused about the following output in this linked list
class ListNode{
public $next = NULL;
public $data = NULL;
public function __construct($data){
$this->data = $data;
}
}
class LinkedList{
private $firstNode = NULL;
private $lastNode = NULL;
public function insertFirst($data){
$link = new ListNode($data);
$link->next = $this->firstNode;
$this->firstNode = &$link;
if($this->lastNode == NULL){
$this->lastNode = &$link;
}
}
public function readList(){
while($this->firstNode != NULL){
echo $this->firstNode->data;
$this->firstNode = $this->firstNode->next;
}
}
public function assessList(){
$copy = $this->firstNode;
echo $copy->data;
echo $this->firstNode->data;
$copy->data = 'm';
echo $copy->data;
echo $this->firstNode->data;
}
}
$linkedList = new LinkedList();
$linkedList->insertFirst('c');
$linkedList->insertFirst('b');
$linkedList->insertFirst('a');
//$linkedList->readList(); //output a b c
$linkedList->assessList(); //outputs a a m m
I would expect the output to be a a m a. I thought $copy is just a copy of the value stored in $this->firstNode.
Isn't this line of code $copy = $this->firstNode an assignment by value? I would expect the output to be a a m m if it was an assignment by reference $copy = &$this->firstNode but not if it was an assignment by value.
Can someone please clarify?
EDIT (additional example)
public function assessList(){
$copy = $this->firstNode->data;
echo $copy. "<br/>";
echo $this->firstNode->data. "<br/>";
$copy = 'm';
echo $copy. "<br/>";
echo $this->firstNode->data. "<br/>";
}
This:
$copy = $this->firstNode;
Is not a copy of the object, it's a copy of the "pointer" to the original object, so when you modify it, you modify the underlying object. You need to use the clone keyword to get a true copy:
$copy = clone $this->firstNode;
From the PHP docs (emphasis mine):
When assigning an already created instance of a class to a new
variable, the new variable will access the same instance as the object
that was assigned.
You can see from this example that your code snippet now outputs:
aama
I have set an array in my config file that I use global in my functions.
This works fine, but now I want to pass the name of this array as a #param in my function.
// in config file:
$album_type_arr = array("appartamento", "villa");
global $album_type_arr; // pull in from db_config
echo $album_type_arr[0];
function buildmenu($name) {
$test = global $name . "_arr";
echo $test[0];
}
buildmenu("album_type");
You're looking for variable variables:
http://www.php.net/manual/en/language.variables.variable.php
function buildmenu($name) {
$test = $name . "_arr";
global ${$test};
echo ${$test}[0];
}
You can use "variable variables". This works:
function buildmenu($name) {
global ${$name. '_arr'};
$test = ${$name. '_arr'};
echo $test[0];
}