PHP - Get object properties by variable - php

I have an object with lots of properties. Some of the properties have their names start with the same string of text (in my example to come "bullet"), followed by an integer.
I can fetch the property values as follows:
echo $objectName->bullet1;
echo $objectName->bullet2;
echo $objectName->bullet3;
and so on.
I'm trying to write a for loop to get the first 20 of these, and at the moment it looks a bit like:
for ($i = 1; $i <= 20; $i++){
if ($objectName->bullet$i){
echo $objectName->bullet$i;
}
}
But this isn't working. I know I could write something like
$bulletsArray[1] = $objectName->bullet1;
$bulletsArray[2] = $objectName->bullet2;
$bulletsArray[3] = $objectName->bullet3;
all the way through to 20, then put a for loop on that, but I'm sure there must be a cleaner way. Can someone point me in the right direction?

This is how you can do it:
for ($i = 1; $i <= 20; $i++){
$propertyName = "bullet$i";
if ($objectName->$propertyName){
echo $info->$propertyName;
}
}
Though I think using an array instead of the object would be a better solution.

$var = 'myVariable';
$value = $object->$var;
is the correct syntax for accessing a field by name in PHP.
In your case it would look something like this:
for ($i = 1; $i <= 20; $i++)
{
$var = 'bullet'.$i;
if ($objectName->$var)
{
echo $info->$var;
}
}

Both previous answers have the "try it, if it doesn't work, move on" and are working for a very specific situation. Let me give you a more generic approach, which, sadly, requires PHP 5.
A bit about Reflection
Reflection allows you to reflect on an object or class to extract useful information about it. In particular, you can use Reflection to get all the properties set in a class, whether static, at run-time, or generated on the go.
To do this, start by initiating your Reflection object (assuming your class object is $object) as follows:
$refObj = new ReflectionObject($object);
This will now give you a reflection interface. Notice the useful ReflectionObject::getProperties() method - it allows you to get all properties set in a class (and you can filter by public, protected, private etc... if needed). We'll use exactly this:
$yourNewArray = array();
$PropertyArray = $refObj->getProperties();
$pCount = count($PropertyArray);
for ($i = 0; $i < $pCount; $i++) {
$yourNewArray[$PropertyArray[$i]->getName()] = $PropertyArray[$i]->getValue($object);
}
Done. Completely generic, works anywhere.

in my system, which doesn't allow me to do
$myPropertyValue = $object->$property;
I still can get to the value of the 'variable' property name with the function below; you can set $property without php complaining about syntax or throwing errors.
<?php
class MyClass{
public function getProperty($propertyName){
$props=get_object_vars($this);
if (array_key_exists($propertyName,$props)){
return $props[$propertyName];
}else{
return FALSE;
}
}
}
?>

Related

How to let user, by text input, choose which function to use

How can I let a user (e.g. admin), by text input, choose which function to use?
I have really tried to think of a solution for this, and I really don't want to use eval, I can't even use it anyways because it is disabled (which is good), but I need the user to be able to specify what function the program needs to perform for a couple of times.
It is a general function that allows you to choose which function you want to perform, and then performs the function a lot of times.
Let me give an example that should work: (but I don't want to do this, because it uses eval, and eval is also disabled)
function generate_random_integer($a, $b) {
...
}
function rinse_and_repeat($array, $count) {
$function_name = $array[0];
$params = $array[1];
$param_string = implode(",", $params);
$query= '$function_name($param_string);';
$total = 0;
for($i = 0; $i < $count; $i++) {
$value = eval($query);
if($verbose) { print($value); }
$total += $value;
}
$ratio = $total/$count;
return($total);
}
$input = array("generate_random_integer", array(1, 10));
$total = rinse_and_repeat($input, 100);
Don't stare blind on the "generate_random_integer", I know I can do that with other functions, but I want a general solution for letting the user choose which function to perform.
How do I make something similar to this, without using eval?
Can you only do this with eval or similar functions?
If you are using OOPs, you can probably make use of strategy design pattern, which is a good practice. Using this pattern you can create object of a class based on user input
Create different class for each user input, so that you can create object of that particular class. All methods that depend on user input can go into that class.
https://refactoring.guru/design-patterns/strategy/php/example

How do you print a variable in PHP that's either one element of an array, or the whole variable if it's not an array

Say I have $exampleVariable, which I want to print. $exampleVariable may be an array, in which case I have this set up to get the right array element, which I can then print with print $exampleVariable[$i].
if ($_GET) {
$i = array_search($_GET["exampleQueryString"], $exampleVariable);
} elseif (is_array($exampleVariable)) {
$i = 0;
} else {
$i = "";
}
My problem is that last else, if $exampleVariable is NOT an array, because then I get print $exampleVariable[] which doesn't work. So is there something I can put as $i to print the whole variable?
Alternatively, I considered including the brackets in $i, so I'd have for example $i = [0];, but in that case I don't know how I'd print it. $exampleVariable$i certainly won't work.
I have a good number of variables besides $exampleVariable I'll need to print, all with the same $i or lack thereof, so I'd like to not have to do anything longwinded to set each of them up individually.
This sounds way more complicated than I feel like it should, so hopefully it makes sense!
You can always do a nifty thing that is called type casting. That means, that you can always make a variable an array even if it is not, by prepending its name by (array):
$exampleVariable = (array)$exampleVariable;
So you don't need three if branches at all:
if ($_GET) { 
$i = array_search($_GET["exampleQueryString"], $exampleVariable);
} else {
$i = 0;
$exampleVariable = (array)$exampleVariable;
}
You could apply the (array) cast, which will have no effect if the target is already an array:
$i = array_search($_GET["exampleQueryString"], (array)$exampleVariable);

Function calls within a loop when its not necessary PHP

This might be a very dumb question but it still bugs me. I tend to use this:
$variable = $someObject->getSomeValue();
for ($i = 0; $i < $x; $i++) {
performSomeFunction($variable);
}
I have seen people do the following & some of my co-workers are arguing with me that there is no difference in performance if I use function calls within a loop & that it will save 1 line of code.
for ($i = 0; $i < $x; $i++) {
performSomeFunction($someObject->getSomeValue());
}
Now for $x = 10 this might not have impact on performance but what if $x = 10000 ? Which one is the preferred way or best practice in PHP and in Programming general?
Example of function getSomeValue
// just a getter method for the class
function getSomeValue() {
return $this->userFirstName;
}
Highly depends on your function. For example this
function() {
return 2;
}
It won't matter.
For this:
function() {
$pdo->query('SELECT ....');
// more db stuff
return $someDbStuff;
}
It will matter extremely!
Depends on what you do on $someObject->getSomeValue();. If just returns a variable, it doesn't have any impact on performance, if, on the other hand, you are retrieving the data from a database, its very important to avoid it.
However, its always a good policy to avoid unnecessary iterations and do like this
$variable = $someObject->getSomeValue();
for ($i = 0; $i < $x; $i++) {
performSomeFunction($variable);
}
Yeah, sure there's an impact in the performance.
If you are about to use the same value over iterated loops, why would you go get it every time?
It's better getting it before the loop (if there's no chance of changing this value while in the loop) and then reusing it.
Imagine this getSomeValue() needs to access a database or a webservice, would you rather do it 1 time or $x times for the same effect?

PHP, what is this? (looks like a object function call using dynamic function name)

I want to find a explanation for this code including the name used for it and any offical documentation, but I cant find much on it,
<?php $objects = $this->module->{'GetObjects'.ucfirst($key).'Array'}(); ?>
It seems to be calling a object function using dynamic value. Any documentation on this or tutorials or information?
thanks
It's called 'variable variables'. check this link: http://php.net/manual/en/language.variables.variable.php
When u need to call dynamic methods, you need to put your variable between { }, like in the questions´s example ...
If you are dealing with ordninaries variable, you could use only $$ like:
$var1 = 1;
$var2 = 2;
$var4 = 3;
$var4 = 4;
for ($i = 1; $i < 5; $i++) {
$aux = 'var'.$i;
echo $$aux
}
This above code shpuld print: 1234

PHP access object property through constant's value

I have a Player class which has properties: $infantry, $vehicles and $air.
When battling players, I don't know which property is being used as an array which holds the properties to be used is shuffled to create a random order.
I try to use this, but it doesn't work. Strangely it doesn't give me empty property error so I assume it's pointing to some property:
<?php
$typeOrder = array(_INF_, _VEH_, _AIR_); // _INF_ const = "infantry" etc
$turnOrder = $typeOrder;
shuffle($turnOrder);
for($i = 0; $i < 3; $i++)
{
$attType = $turnOrder[$i];
print $p1->$attType;
}
?>
How do I properly access a property with the value held in a constant?
Thanks.
It should work - as long as $p1->infantry etc exist. What error does PHP give you exactly?
By the way, have a look at array_rand().

Categories