Click to See Complete Forum and Search --> : Problem when pass array into a class constructor


sunnyside
04-24-2007, 03:05 PM
I have a class which has a constructor with an array variable as argument. I can get the correct each array value inside of the constructor, but won't get it outside of the constructor (always get "A", "1" as the each array value).

Code:

function myfunction(
$dataField['a'] = $a;
$dataField['b'] = $b;
$dataField['c'] = $c;

$obj = new MyClass($dataField);
}

class MyClass{
private $myArray = array();

public function __constructor($arrString=array()){
$this->myArray = $arrString;
print_r($this->myArray); // no problem to get all values
}

public function testArray(){
return $this->myArray['a']; /* won't print out "a", display "1", "A", something like that */

}
}

Znupi
04-24-2007, 03:16 PM
1. You have an error in your syntax. The 'myfunction' function is defined incorrectly. You probably meant

function myfunction($a, $b, $c) {
$dataField['a'] = $a;
$dataField['b'] = $b;
$dataField['c'] = $c;

$obj = new MyClass($dataField);
}

2. What is $a, $b and $c?
3. It's __construct, not __constructor:

class MyClass{
private $myArray = array();

public function __construct ($arrString=array()) {
$this->myArray = $arrString;
print_r($this->myArray); // no problem to get all values
}

public function testArray() {
return $this->myArray['a']; /* won't print out "a", display "1", "A", something like that */

}
}

4. Once the myfunction function has finished executing, your $obj object will get deleted. You should use a global var for that:

function myfunction($a, $b, $c) {
global $obj;

$dataField['a'] = $a;
$dataField['b'] = $b;
$dataField['c'] = $c;

$obj = new MyClass($dataField);
}

sunnyside
04-24-2007, 03:27 PM
Sorry, I just wrote part of my function, so didn't write it very careful. Yes, actually I define all the variable ($a, ...) inside of my function

1. You have an error in your syntax. The 'myfunction' function is defined incorrectly. You probably meant...