I have this simple issue. In this simple script:
<?php
class MyClass {
public var1 = '1';
public var2 = '';
public var3 = '3';
}
$class = new MyClass;
foreach ($class as $key => $value) {
echo $key . ' => ' . $value . '<br />';
}
?>
The result would be:
var1 => 1
var2 =>
var3 => 3
If I want to iterate through all those properties so I can find out which one is empty, how can I assign a value to that empty property in the object?
foreach ($class as $key => $value) {
if (empty($value)) {
$value = 'something';
}
}
... is not working because I guess that PHP thinks that $value is an actual variable, not a reference.
Try this:
foreach ($class as $key => $value) {
if (empty($value)) {
$value = 'something';
$class->$key = $value;
}
}
Related
so lets say i have a object like this
{
"status": "AlreadyVerified"
}
and i want to store propert key in variable so i can access property using that variable like
$key = 'status';
echo $object->$key
but what if i have a nested object like
{
"extra_info": {#305 ▼
+"status": "AlreadyVerified"
}
}
this wouldn't work
$key = 'extra_info->status';
echo $object->$key
how can i store nested object chain in a variable so i can access its property using that variable ?
preferably some way that works for both nested and flat objects (i guess that's what the're called !)
It can be possible by write helper function like this:
function deepFind($o, $key) {
$key = explode('->', $key);
$value = $o;
foreach ($key as $i=>$k) {
if (is_object($value) && isset($value->{$k})) {
$value = $value->{$k};
} elseif (is_array($value) && isset($value[$k])) {
$value = $value[$k];
} elseif ($i == count($key) - 1) {
$value = null;
}
}
return $value;
}
Usage:
$o = (object)[
"extra_info" => (object)[
"status" => "AlreadyVerified"
]
];
echo deepFind($o, 'extra_info->status');
Online demo
This is one way to do it, albeit potentially insecure depending on where $key comes from:
<?php
$object = new stdClass();
$object->extra_info = new stdClass();
$object->extra_info->status = 'AlreadyVerified';
$key = 'extra_info->status';
eval( 'echo $object->'.$key.';' );
Output:
AlreadyVerified
Additionally, if you wanted to parse $key then you could use a recursive function to access the nested value.
I have an employee class and i want to initialize the employee object from mongodb.findone() returned array.
foreach($res as $key => $value){
echo $value; // here values printed
}
but i need to do something like( if key = 'first_name' then employee_obj->set_first_name($value), if key = 'last_name' then employee_obj->set_last_name($value)... ) can you help me?
$employee = new Employee;
foreach($res as $key => $value){
if (property_exists($employee, $key)) {
$employee->$key = $value;
}
}
$employee->$key = $value is dynamically assigning $key property to the employee. Example:
$key = "name";
$employee->$key = "John Doe";
echo $employee->name; // John Doe
If you want to do this with private or protected properties you need to do the assignment within the class or instance:
class Employee {
// ...
private $name;
// lets you assign properties by passing in an array
public function __construct($arr = array()){
if count($arr) {
foreach($arr as $key => $value){
if (property_exists($this, $key)) {
$this->$key = $value;
}
}
}
}
}
$joe = new Employee(array('name' => 'Joe'));
echo $joe->name // Joe
$e = new Employee;
foreach($res as $k => $v){
if($k == 'first_name'){
$e->set_first_name($v);
}elseif($k == 'last_name'){
$e->set_last_name($v);
}else{
$e->$k = $v;
}
}
Does exactly that.
I've got this function:
$request = array("setNewDoc", "setNewFile");
foreach($request as $key => $val) {
$result = $controller->setNewDoc($key);
$smarty->assign('result', $result);
$index = TPL_DIR . 'docs.tpl';
}
Is it possible to make this loop dynamic with putting a variable in my pointer? The $keys in my array are also the name of the function.
Like $controller->$variable($key);
Like this(pseudo code)
$result = array("setNewDoc", "setNewFile");
foreach($request as $key => $val) {
$result = $controller->set$key($request);
$smarty->assign('result', $result);
// $key = setNewDoc or setNewFile
$index = TPL_DIR . $key . '.tpl';
}
Yes you can.
You can use it to cast a new object or to acces a property.
For exmaple
$classname = foo;
$prop=name;
$myObject = new $classname();
$myObject->{$prop} or a function: $myObject->{$prop}()
You can even foreach over an object's properties
foreach ($myObject as $key => $value) {
print $key // would be name
print $value // would be the value of the property
}
Yes that's possible and it is in fact pretty easy:
<?php
class MyClass {
function myMethod()
{
echo "Hello World";
}
}
$obj = new MyClass();
$dynamicVar = 'Method';
$obj->{'my' . $dynamicVar}();
enclose your method name with curly brackets and you can do some string concatenation inside. Once everything inside the the brackets is processed it will eventually used as your method name.
For your specific use case you would write something like
<?php
$result = array("setNewDoc", "setNewFile");
foreach($request as $key => $val) {
$result = $controller->{'set' . $key}($request);
$smarty->assign('result', $result);
// $key = setNewDoc or setNewFile
$index = TPL_DIR . $key . '.tpl';
}
how to print dynamical add properties in bellow class?
class Car {
function __construct() {
}
function setInfo($car_arr) {
foreach ($car_arr as $key => $value) {
$this->{$key} = $value;
}
}
}
set class object like bellow
$car1 = new Car();
$car1->setInfo(array('make' => 'Toyota', 'model' => 'scp10'));
$car2 = new Car();
$car2->setInfo(array('anme1' => 'value1', 'anme2' => 'value2'));
now I want to to print car object bellow
make = Toyota
model = scp10
Try :
$car1 = new Car();
$car1->setInfo(array('make' => 'Toyota', 'model' => 'scp10'));
echo $car1->make;
echo $car1->model;
<?php
class Car {
function __construct() {
}
function setInfo($car_arr) {
foreach ($car_arr as $key => $value) {
$this->{$key} = $value;
}
}
}
$car1 = new Car();
$car1->setInfo(array('make' => 'Toyota', 'model' => 'scp10'));
echo "Make value is : " . $car1->make. ", Model value is : ". $car1->model;
?>
above code output Make value is : Toyota, Model value is : scp10
Please consider storing the properties explicitly like I pointed out in this answer:
<?php
class Car {
private $data = array();
function setInfo(array $carInfo) {
foreach ($carInfo as $k => $v) {
$this->data[$k] = $v;
}
return $this;
}
function __set($key, $val) {
$this->data[$key] = $val;
}
function __get($key) {
return $this->data[$key];
}
}
$car = new Car();
$car->setInfo(array('make' => 'Toyota', 'warranty' => '5 years'));
I'd consider it more "clean", but that's probably debatable.
I think you look for something like this PHP Magic Methods
For example this one:
<?php
class A
{
public $var1;
public $var2;
public static function __set_state($an_array) // As of PHP 5.1.0
{
$obj = new A;
$obj->var1 = $an_array['var1'];
$obj->var2 = $an_array['var2'];
return $obj;
}
}
$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';
eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
// 'var1' => 5,
// 'var2' => 'foo',
// ));
var_dump($b);
?>
This will be helpful too.
You can fetch all properties using get_object_vars():
$vars = get_object_vars($car1);
foreach ($vars as $key => $value) {
echo $key . ' = ' . $value . '<br />';
}
I'm trying to access third party api which gives me object and sub object, for example:
stdClass Object
(
[truncated] =>
[text] => "some text"
[user] => stdClass Object
(
[count] => 9370
[comments_enabled] => yes
When I try and loop through the object with the following code I get an error at the start of sub-object 'user'. Can anyone help me either 1) iterate through the sub-object, or 2) block the sub-object from the loop.
The code:
$test = $s[0];
$obj = new ArrayObject($test);
foreach ($obj as $data => $name) {
print $data . ' - ' . $name . '<br />';
}
thanks
It's because the 'user' field is an object, so you need to separately run through each field within that object
function iterateObject($obj, $name='') {
//for each element
foreach ($obj as $key=>$val) {
$myName = ($name !='') ? "$name.$key" : $key;
//if type of the element is an object or array
if ( is_object($val) || is_array($val) ) {
//if so, iterate through its properties
iterateObject($val, $myName);
}
//otherwise output name/ value combination
else {
print "$myName - $val <br/>";
}
}
}
$test = $s[0];
$obj = new ArrayObject( $test );
iterateObject( $obj );
Will output
truncated -
text - some text
user.count - 9370
user.comments_enabled - yes
This will iterate through a tree of objects and print key - value pairs...
printObject($test);
function printObject($obj) {
foreach (get_object_vars($obj) as $field => $value) {
if (is_object($value)) {
printObject($value);
} else {
print $field . ' - ' . $value . '<br />';
}
}
}
<?php
function traceObject($object) {
foreach ($object as $data => $name) {
if (is_object($name)) {
traceObject($name);
} else {
echo $data . ' - ' . $name .'<br />';
}
}
}