14. Consider the following segment of PHP code. When it is executed, the string returned by the $eight_tenths->to_string method is 8 / 10 instead of the expected 4 / 5. Why?
<?php
class fraction {
var $numerator;
var $denominator;
function fraction($n, $d) {
$this->set_numerator($n);
$this->set_denominator($d);
}
function set_numerator($num){
$this->numerator= (int)$num;
}
function set_denominator($num) {
$this->denominator = (int)$num;
}
function to_string() {
return "{$this->numerator}
/ {$this->denominator}";
}
}
function gcd($a, $b) {
return ($b > 0) ? gcd($b, $a % $b) : $a;
}
function reduce_fraction($fraction) {
$gcd= gcd($fraction->numerator,
$fraction->denominator);
$fraction->numerator /= $gcd;
$fraction->denominator /= $gcd;
}
$eight_tenths = new fraction(8,10);
/* Reduce the fraction */
reduce_fraction($eight_tenths);
var_dump($eight_tenths->to_string());
?>
Вариант ответа 1 - A) The reduce_fraction function must return a value
Вариант ответа 2 - B) The reduce_fraction function should accept integer values
Вариант ответа 3 - C) The gcd function is flawed
Вариант ответа 4 - D) You must pass the $eight_tenths object by-reference
Вариант ответа 5 - E) You cannot pass instances of objects to anything but methods
Комментарий: In PHP, objects that are passed to a function or method are, by default, passed by value, meaning the object used within the function is actually a copy of the object that was passed as a parameter. This unfortunate side effect means that any modifications to the object performed within the context of the function or method call will not apply to the original object outside of the function’s scope. In the case of Question 14, this means that the $eight_tenths object was never altered by the reduce_fraction function, while the $fraction object (the parameter) was. An object that may be modified inside a function should be always passed to it by reference: function reduce_fraction(&$fraction) Thus, the correct answer is D.