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
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);
I was given a quiz by an employer to determine my ability as a programmer and the test was more or less "Write a function that counts the length of this linked list". I failed the quiz because for whatever reason my function didn't return anything (It was a timed quiz). This is my code.
class IntList{
var $value = 1;
var $next = null;
}
$A = new IntList();
$B = new IntList();
$C = new IntList();
$D = new IntList();
$A->next = $B;
$B->next = $C;
$C->next = $D;
main($A);
$count = 0;
function main($L)
{
global $count;
$final = getListLength($L, $count);
print $final;
}
function getListLength($L, $count)
{
if (isset($L->next))
{
$count++;
getListLength($L->next, $count);
} else
{
print $count;
return $count;
}
}
in getListLength im getting 3 when i print count before the return statement. But after the function returns I'm left with no output. I feel really stupid right now. Any thoughts?
Assuming this is the code from the quiz (argh, PHP4 --'):
class IntList{
var $value = 1;
var $next = null;
}
$A = new IntList();
$B = new IntList();
$C = new IntList();
$D = new IntList();
$A->next = $B;
$B->next = $C;
$C->next = $D;
I don't think you need recursion to solve that. You could just:
function getListLength($list) {
$count = 0;
$item = $list;
while($item instanceof IntList) {
$count++;
$item = $item->next;
}
return $count;
}
You just forgot to put global $count; in the second function.
Also, if you want to count the last one, you should move the $count++ outside of the conditional.
Here's a fiddle.
Alternatively, you can pass the $count variable by reference
function getListLength($L, &$count){...}
Another fiddle..
Since you are trying to use recursion here, I think the only thing that is missing is that your recursive case is not returning. You really should not need global. If you need to start at zero, you can give your getListLength a default count, or explicitly call it with zero in main.
function main($L) {
$final = getListLength($L);
print $final;
}
function getListLength($L, $count = 0) {
if (isset($L->next)) {
$count++;
// this case should return
return getListLength($L->next, $count);
} else {
return $count;
}
}
There are 3 compilation errors in the init.php code:
Undefined variable $ind
Undefined variable $popsize
Undefined variable $chrom
How to solve this issue in the proper way?
main.php
include_once 'init.php';
class Individual {
public $genes = array();
//...
}
class Population {
public $ind = array();
public $ind_ptr;
public function setIndPtr(Individual $ind) {
$this->ind_ptr = $ind;
}
}
$popsize = 10;
$chrom = 5;
$pop = new Population();
$pop_ptr = new Population();
$pop = init(pop_ptr);
init.php
function init(Population $pop_ptr) {
$pop_ptr->setIndPtr($ind[0]);
for ($i = 0 ; $i < $popsize ; $i++) {
for ($j = 0; $j < $chrom; $j++) {
$d = rand(0,1);
if($d >= 0.5) {
$pop_ptr->ind_ptr->genes[$j] = 1;
}
else {
$pop_ptr->ind_ptr->genes[$j] = 0;
}
}
$pop_ptr->setIndPtr($ind[$i+1]);
}
$pop_ptr->setIndPtr($ind[0]);
return $pop_ptr;
}
Its a matter of scope: Variables are not shared over files, unless you make them global!
(Badly explained) variables such as
inc.php
$a=1;
main.php
include "inc.php";
print $a
would work
however
inc.php
function func()
{
$a=1;
}
main.php
include "inc.php";
func();
print $a;
a is not available.
Hope that makes it clearer.
Global variables in function scope need to be declared explicitly global before use:
<?php
function foo()
{
global $global_variable_from_outside_function_scope;
$global_variable_from_outside_function_scope += 1;
}
As for $ind, there's no such variable there. You want something more akin to $pop_ptr -> ind. Read the PHP docs again on classes, scope, etc..
Program that tests the rand function is an example:
<?php
class number {
function number() {
$occurences=0;
}
public $occurences;
public $value;
}
$draws = 5000;
$numOfInts = 10;
//$integers = array();
$integers [] = new number();
//initialising loop
for($i=0;$i<=$numOfInts;$i++)
$integers[$i]->$value = $i; //debugger points here
for($i=0;$i<$draws;$i++) {
$integers[rand(0,numOfInts)]->$occurences++;
}
foreach($integers as $int)
printf("%5d %5d <br/>",$int->$value,$int->$occurences);
?>
Errors on the WAMP server:
Undefined variable: value in C:\path\index.php on line 31
Fatal error: Cannot access empty property in C:\path\index.php on line 31
What caused them and how to fix it? I suppose that the $integers is declared incorrectly.
You should access members of an object with this syntax:
$integers[$i]->value
$integers[$i]->occurences;
However you have to initialize your array first as well which means un-comment the initial line to
$integers = array();
As a matter of fact you are not using the better OOP style which would change your data structure like this:
class Number {
private $value;
private $occurences = 0;
public function __construct($value = 0) {
$this->value = $value;
}
public function getValue() {
return $this->number;
}
public function addOccurence() {
$this->occurences++;
}
public function getOccurences() {
return $this->occurences;
}
}
You would then access the members like this:
// init part
$integers = array();
for($i = 0; $i < $numOfInts; $i++) {
$integers[] = new Number($i);
}
// draws part
for($i=0; $i < $draws; $i++) {
$integers[rand(0,$numOfInts-1)]->addOccurence();
}
// print part
foreach($integers as $number) {
printf("%5d %5d<br />", $number->getValue(), $number->getOccurences());
}
Why?
//$integers = array();
$integers [] = new number();
Should just be
$integers = array();
for($i=0;$i<=$numOfInts;$i++) {
$integers[$i] = new number();
}
There are no typed arrays in PHP
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;
}