ndakota
07-06-2008, 14:45
Ciao a tutti, sto leggendo un articolo della rivista "io programmo" che tratta il pattern value object. L'articolo è scritto in ruby ma io lo voglio tradurre in php.
Ho la classe Money che è così:
<?php
class Money {
public $cents;
function __construct($euros, $cents) {
$this->cents = $euros * 100 + $cents;
}
function add($other_money) {
$this->cents += $other_money->cents;
}
function sub($other_money) {
$this->cents -= $other_money->cents;
}
function __toString() {
return (int)($this->cents / 100) . "," . $this->cents % 100 . "€";
}
}
?>
E la classe Account che è così:
<?php
require_once('money.class.php');
class Account {
public $money;
function __construct($owner, $money) {
$this->owner = $owner;
$this->money = $money;
}
function __toString() {
return $this->owner . " possiede " . $this->money;
}
}
?>
e poi un index che testa il tutto che è così:
<?php
require('account.class.php');
$a = new Account("faggot", new Money(2, 50));
$b = new Account("pirla", new Money(2, 50));
$a->money->add(1, 0);
echo $a;
?>
ora in questo caso si dovrebbe avere un problema di aliasing cioè verrebbe aggiunto 1,0 euro a entrambi i conti quando dovrebbe essere aggiunto solo a faggot però io non riesco a verificarlo in quanto mi da errore alla riga della funzione add della classe Money e mi stampa 2,50€, senza aggiunta quindi.. qualcuno sa dirmi dove sbaglio?
Ho la classe Money che è così:
<?php
class Money {
public $cents;
function __construct($euros, $cents) {
$this->cents = $euros * 100 + $cents;
}
function add($other_money) {
$this->cents += $other_money->cents;
}
function sub($other_money) {
$this->cents -= $other_money->cents;
}
function __toString() {
return (int)($this->cents / 100) . "," . $this->cents % 100 . "€";
}
}
?>
E la classe Account che è così:
<?php
require_once('money.class.php');
class Account {
public $money;
function __construct($owner, $money) {
$this->owner = $owner;
$this->money = $money;
}
function __toString() {
return $this->owner . " possiede " . $this->money;
}
}
?>
e poi un index che testa il tutto che è così:
<?php
require('account.class.php');
$a = new Account("faggot", new Money(2, 50));
$b = new Account("pirla", new Money(2, 50));
$a->money->add(1, 0);
echo $a;
?>
ora in questo caso si dovrebbe avere un problema di aliasing cioè verrebbe aggiunto 1,0 euro a entrambi i conti quando dovrebbe essere aggiunto solo a faggot però io non riesco a verificarlo in quanto mi da errore alla riga della funzione add della classe Money e mi stampa 2,50€, senza aggiunta quindi.. qualcuno sa dirmi dove sbaglio?