Please explain me why that code:
class kategoria
{
public $IdKat;
public $NazwaKat;
public $OpisKat;
}
class dbClass
{
private $link;
private $user = USER;
private $pass = PASS;
private $database = DATABASE;
function __construct()
{
try
{
$this->link = new mysqli('localhost', $this->user, $this->pass, $this->database);
$this->link->set_charset('utf8');
;
}
catch(Exception $exc)
{
echo $e;
}
}
function get_cats()
{
$query = "SELECT IdKat, NazwaKat, OpisKat FROM `kategorie`";
try
{
$stmt = $this->link->prepare($query);
/* bind parameters for markers */
//$stmt->bind_param("i", $IdKat);
$stmt->execute();
$kat = new kategoria();
$stmt->bind_result(
$kat->IdKat,
$kat->NazwaKat,
$kat->OpisKat
);
$output = array();
$output2 = array();
while ($stmt->fetch()) {
array_push($output, $kat->IdKat);
array_push($output2, $kat);
// array_push($output2, clone $kat); // i tried cloning like this
// $output2 += array(clone($kat)); // tried adding
}
$stmt->close();
}
catch (Exception $e)
{
echo $e;
}
echo '<pre>';
print_r($output);
echo '</pre>';
echo '--------------------------<br/>';
echo '<pre>';
print_r($output2);
echo '</pre>';
}
}
Gives me data like this:
Array (
[0] => 2
[1] => 3
[2] => 4 )
--------------------------
Array (
[0] => kategoria Object
(
[IdKat] => 4
[NazwaKat] => Hi-Fi
[OpisKat] => Music equipment
)
[1] => kategoria Object
(
[IdKat] => 4
[NazwaKat] => Hi-Fi
[OpisKat] => Music equipment
)
[2] => kategoria Object
(
[IdKat] => 4
[NazwaKat] => Hi-Fi
[OpisKat] => Music equipment
)
)
This is my second question about it. I tried adding arrays, cloning object $kat and it didnt worked. Finally i made another array and im using both for debugging.
It looks weird. I dont understand why cloned object in array is overwriten after next row fetching. It supposed be a copy of his clone, right?
I found answer in PHP help. I had to create “deep copy” like this:
Because (i believe) help says: “Any properties that are references to other variables, will remain references.”