I would like to access class variables with for loop, here is my simple class
class test{
public $var1 = 1;
public $var2 = 2;
public $var3 = 3;
public $var4 = 4;
}
$class = new test();
this is how i try to access variables with a loop
for($i = 1; $i <= 4; $i++){
echo $class->var.$i;
}
and i get error which says
Notice: Undefined property: test::$var in C:\xampp\htdocs\test\index.php on line 12
Well it's not really a big error and i actualy get the value echoed but i still don't understand why do i get this error?
also if i do it this way everything works fine:
echo $class->var1;
for($i = 1; $i <= 4; $i++){
$var = 'var' . $i;
echo $class->$var;
}
Or, as mentioned in the comments, this will work in newer versions of PHP
for($i = 1; $i <= 4; $i++){
$class->{'var' . $i}
}
You're not actually getting the value echoed, you're getting $i echoed.
echo $class->var.$i; is being interpreted as echo ($class->var).($i);. Since var isn't a variable (hence the error), it becomes echo ''.$i;, so you get the value of $i. It just so happens that var1 has the value 1. (Change $var1 to something else, and you'll see what I mean)
To fix the issue, you can do this:
for($i = 1; $i <= 4; $i++){
$class->{'var'.$i}
}
The stuff inside the {} is calculated first, so the correct property is read.
The code isn't doing what you think. It's only echoing 1-4 because of your $i in the for loop. If you were to change the vars in the class, your output will still be 1-4.
The undefined property notices is the clue: it is trying to access the property var.
If you want to store data that is repetitive and/or associated, especially like in your example, it is usually more suitable to store as an array:
class test{
public $vars;
public function __construct()
{
$this->vars = array(1, 2, 3, 4);
}
}
$obj = new test();
foreach($obj->vars as $var)
{
echo $var;
}
The dot (.) operator is getting used by the echo rather than the member call to $class.
One of many solutions:
for($i = 1; $i <= 4; $i++){
echo $class->{'var'.$i};
}
live example here
This already works fine on very recent PHP versions, but try this:
for($i = 1; $i <= 4; $i++){
$v = 'var'.$i;
echo $class->$v;
}
Related
I am new to PHP and am trying to remove duplicate entries in an array. I end up with my desired output, but I am also getting two "Undefined offset" errors along the way. This is the code I have:
$this->master refers to an array declared in the beginning of the class.
public function removeDuplicates(){
$var = count($this->master);
for($i = 0; $i < $var; $i++){
for($j = 0; $j <$var; $j++){
if(($this->master[$i] == $this->master[$j]) && $i != $j){
$this->shiftLeft($j, $var);
$var --;
}
}
}
}
public function shiftLeft($t, $s){
while($t < $s){
echo "$t ";
$this->master[$t] = $this->master[$t+1];
$t++;
}
unset($this->master[$t-1]);
}
It is probably a really simple logical error but I cannot seem to find where. Any help is greatly appreciated.
See if it works
$unique = array_unique($this->master);
This is basic stuff but I seem to be way too beginner to make it work. Down here I would like to somehow get my 100 arrays into different sessions, but anything like that does not seem to work and I wonder why?
for($i=1; $i<=100; $i++) {
$age = rand(1,100);
$table[] = $age;
$_SESSION[$i] = $table[];
}
Later I need to be able to echo $age of all 100 sessions printed also using for loop. If I do like down there again it just says about undefined override and gives number of all 100 $i's.
for($i=1; $i<=100; $i++) {
echo $_SESSION[$i];
}
for($i=1; $i<=100; $i++) {
$age = rand(1,100);
$ages[] = $age;
}
$_SESSION['ages'] = $ages;
In your other script
$ages = $_SESSION['ages'];
foreach($ages as $age) {
echo $age;
}
You can do like this:
for($i=1; $i<=100; $i++) {
$age = rand(1,100);
$table[] = $_SESSION["ages"][$i] = $age;
}
You cannot work with $_SESSION as if it were a normal array, it isn't. You may not use numeric indexes when using $_SESSION. The below code is completely invalid and will cause notices and may potentially cause your $_SESSION to not be populated you expect
// bad code!
$_SESSION[1] = 'foo'; // error
$_SESSION[] = 'bar'; // error
for ($i = 1; $i <= 100; $i++) {
$_SESSION[$i] = rand(1, 100); // error 100x
}
Like Bram Gerritsen suggest in his answer I would change the code to be something like:
for($i=1; $i<=100; $i++) {
$age = rand(1,100);
$ages[] = $age;
}
$_SESSION['ages'] = $ages;
Fore more information check out this PHP bug report.
I'm working on another developers old code and there are tons of Notice: Undefined index errors when data is being set using the += operator. Essentially the index is not set yet in the array so the error is generated.
Example:
$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
$myArray['test'] += 1;
}
Will generate an error on the first run since the test index is not set yet.
I know I can remove this error with the following code:
$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
if ( ! isset($myArray['test']) )
{
$myArray['test'] = $myValue;
}
else
{
$myArray['test'] += $myValue;
}
}
However, there are around 50 of things like this to change. Is it worth writing all these isset statements or is there a better way I am not aware of?
EDIT: I should note that the array indexes aren't always the same and sometimes aren't set so I can't preset the index in this circumstance to avoid the error.
This is a bit shorter, but perhaps still a bit complicated if you have many edits.
$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
isset($myArray['test']) ? $myArray['test'] += $myValue : $myArray['test'] = $myValue;
}
You could also write a global function (not tested)..
$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
increment($myArray['test'], $myValue);
}
function increment(&$var, $inc){
$var = isset($var) ? $var += $inc : $var = $inc
}
If you are using PHP 7 and above, you can use the Null Coalescing Operator to make this code cleaner.
$myArray = [];
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
$myArray['test'] = $myValue + ($myArray['test'] ?? 0);
}
The benefit here is not only that the code is cleaner, but you're also being more explicit about the default value (0)
Old/Deprecaded/Unrecommended but the shortest solution is
#$myArray['test'] += $myValue;
I'm trying to initialize a class attribute within a php constructor method, but am getting the error:
Notice: Undefined variable: _board in C:\wamp\scaleUp\back\objects.php on line 9
code:
<?php
class Board {
public function __construct(){
for ($x = 9; $x >= 0; $x--) {
for ($y = 0; $y<10; $y++){
$row = array();
$row[$y] = $y;
}
$this->$_board = array();
$this->$_board[$x] = $row;
}
echo "here";
echo $this->$board[$x];
}
}
$board = new Board();
?>
The syntax to access an object field is $obj->field, not $obj->$field (unless you want to access the field name that is stored in $field).
Here, I have debugged the code for you.
<?php
class Board {
public $_board;
public function __construct(){
for ($x = 9; $x >= 0; $x--) {
for ($y = 0; $y<10; $y++){
$row = array();
$row[$y] = $y;
}
$this->_board = array();
$this->_board[$x] = $row;
}
echo "here";
echo $this->_board[$x+1];/*OR*/print_r($this->_board[$x+1]);
//$x had to be incremented here.
}
}
$board = new Board();
?>
As others mentioned, you have to follow the syntax: $obj->property, not $obj->$property.
remove the $ from _board -
$this->_board = array();
It should be
$this->board
You don't need the second $ sign.
Also, in your constructor, in the inner loop, you are re-initializing $row as an array in every iteration. Is that intended?
You have to define your variable as a member variable
suck as
class object {
$_board ;
...
...
...
}
and when you want to use it you have to use the following syntax
$this->_board = .....;
I hope this helps you
For example, what's the difference between
$foobar = 0
for ($i=0; $i<20; $i++) {
//do something using $foobar
$foobar++;
}
and
for ($i=0; $i<20; $i++) {
static $foobar = 0
//do something using $foobar
$foobar++;
}
???
Both of the above examples have different results than from the following:
for ($i=0; $i<20; $i++) {
$foobar = 0
//do something using $foobar
$foobar++;
}
All three variations have a different outcome. I understand that in the first of the three examples the value of the $foobar variable gets larger and larger and that in the third example the value of the $foobar variable gets reset during each loop. I'm not sure what's going on with the example using the static $foobar variable. It would seem that the first two examples should behave the same in the portion of the for loop where $foobar is used, but that is not the case for me.
For reference, here's my actual code (the algorithm is not complete yet). I've marked the for() loop that has me thinking about this topic:
function combine($charArr, $k) {
$currentsize = sizeof($charArr);
static $combs = array();
static $originalsize = "unset";
if ($originalsize === "unset") $originalsize = $currentsize;
static $firstcall = true;
if ($originalsize >= $k) {
$comb = '';
if ($firstcall === true) {
for ($i = $originalsize-$k; $i < $originalsize; $i++) {
$comb .= $charArr[$i];
}
$combs[] = $comb;
$firstcall = false;
}
if ($currentsize > $k) {
$comb = ''; //reset
for ($i=0; $i<$k; $i++) {
$comb .= $charArr[$i];
}
$combs[] = $comb;
//########### THE FOR LOOP IN QUESTION ###########
for ($i = $k-1; $i >= 0; $i--) {
static $range_adj = 0;
for ( $j = $i+1; $j < $currentsize-$range_adj; $j++ ) {
if ( !($i == 0 and $j == $currentsize-$range_adj-1) ) {
$comb = substr_replace($comb, $charArr[$j], $i, 1);
$combs[] = $comb;
}
}
$range_adj++;
}
if ($currentsize-1 > $k) {
array_splice($charArr, 0, 1);
combine($charArr, $k);
}
}
$output = array_values( $combs );
unset($combs);
return $output;
}
else {
return false;
}
}
If I remove the $range_adj variable from for loop and place it right before the said for loop as a none-static variable, then the result of my function is not the same. Here's what the modified for loop would look like:
$range_adj = 0;
for ($i = $k-1; $i >= 0; $i--) {
for ( $j = $i+1; $j < $currentsize-$range_adj; $j++ ) {
if ( !($i == 0 and $j == $currentsize-$range_adj-1) ) {
$comb = substr_replace($comb, $charArr[$j], $i, 1);
$combs[] = $comb;
}
}
$range_adj++;
}
The fact that I get two different outcomes leads me to believe that something is different with each method, because if the two methods produced identical results, then the outcome of my function would be the same in both scenarios, which is not the case when I test these scenarios. Why am I getting two results? Test my function out with both methods of the for loop implemented and you will also get varying results.
For your convenience, here's the original method:
for ($i = $k-1; $i >= 0; $i--) {
static $range_adj = 0;
for ( $j = $i+1; $j < $currentsize-$range_adj; $j++ ) {
if ( !($i == 0 and $j == $currentsize-$range_adj-1) ) {
$comb = substr_replace($comb, $charArr[$j], $i, 1);
$combs[] = $comb;
}
}
$range_adj++;
}
???
It seems to me that the results should be exactly the same, but they are not. If you run my function, you will notice that you get a different result with each method of the for loop.
The first and second loops appear to do the same thing. This is because, as with any other statically-initialized variable, static means you only initialize it once. It retains its value as you try to access it again. You'll find that the static $foobar will still exist outside the scope of the loop wherever you declare/initialize it; this is due to the nature of PHP and has nothing to do with the static variable.
The difference is made clear only when you attempt to access $foobar before the loop: it won't be declared yet in the second snippet because you only create it within the loop, so you may get an undefined-variable notice.
static $foobar = 0;
initializing once, other execute of static $foobar = 0 not do anything with $foobar variable
Above two prog have same output, but your last prog have variable which is reset during each loop.
when you use "Static" key word for any variable initialization then It retains untill you not destroy it.. or not destroy your program session.
You can use static in this fashion to prevent a variable from being reinitialized inside a loop.
in the first iteration if the static variable is not initialize then it would create it and keep it within the outer context, on every other iteration PHP Would just skip it as its already been initialized.
Both results prevail the same: http://codepad.org/evilks4R
The reason why it differs in your function is that your function is recursive which means the function combine calls combine from within itself, when taking out the static keyword on the second call of combine, the variable is being reinitialized thus making the results differ.
using the static keyword allows you to pass the arguments to the second call with there values that was produced in the third value.
here's an example of passing static members to the latter passes of a function call: http://codepad.org/gChjx7Om
if you had done:
$foo_bar = 0;
for(.....)
this would be within a function so that $foo_bar would get reset to 0 every time the function was called, therefore overwriting the last calls calculations.
if you moved the $foo_bar outside the function, and then where needed in the function you added:
global $foo_bar
you would have the same results.
http://www.cprogramming.com/tutorial/statickeyword.html