I'm new to OOP and seem to be stuck on something that i'm sure is very simple, but I don't understand what's happening.
The below example code:
class add_some {
static $arr = array('a', 'b');
static $new_arr = array();
public static function iterate() {
foreach (self::$arr as $v) {
self::$new_arr[] = $v;
}
}
}
for ($i=0; $i < 3; $i++) {
// instantiate the object
$add_some = new add_some;
// launch the method that copies items from $arr to $new_arr
$add_some::iterate();
echo '<pre>';
print_r($add_some::$new_arr);
echo "</pre>";
unset($add_some);
}
Goes through a loop and adds the items which are in $arr to $new_arr, it basically copies all items from $arr to $new_arr
The code instantiates a new object and executes the method iterate() which copies items from $arr to $new_arr 3 times.
Each iteration creates a new object $add_some = new add_some; so each iteration should just produce:
Array
(
[0] => a
[1] => b
Array
(
[0] => a
[1] => b
)
Array
(
[0] => a
[1] => b
)
But for some reason the object keeps growing with each iteration.... And I have no idea why.. I tried destroying the object (unset) and not sure if I should be doing something else.
Array
(
[0] => a
[1] => b
)
Array
(
[0] => a
[1] => b
[2] => a
[3] => b
)
Array
(
[0] => a
[1] => b
[2] => a
[3] => b
[4] => a
[5] => b
)
You are calling the static method by use of the ::
(Paamayim Nekudotayim), you should be using ->
and not using a static function.
Static means, keep this around globally, it is not instantiated each time you call new, it is static
.
You can for example call a static method like so:
class MyClass {
static function MyFunc() { echo 'Stuff'; }
}
MyClass::MyFunc()
There is no need to (nor should you) create an instance of MyClass
to call the static MyFunc
.
Each time you call iterate
it is appending the global static array $arr
The correct way to do this would be
class add_some {
private $x = 1;
private $arr = array('a', 'b');
public $new_arr = array();
public function iterate() {
foreach ($this->arr as $v) {
$this->new_arr[] = $v;
}
}
}
for ($i=0; $i < 3; $i++) {
$add_some = new add_some();
$add_some->iterate();
print_r($add_some->new_arr);
}