I have a simple 'dimensions' class containing a width/height property and a constructor to set them.
I have a function (to re-size dimensions) that takes two dimensions objects -- one to be re-sized, and one containing the max size. It should reduce the dimensions in the first parameter such that they 'fit into' the second parameter.
Then it returns the first, newly resized one.
The caller passes the dimensions object in and gets the return value into a different one -- because it has to preserve the original object. But the one that is passed into the function gets modified.
This was surprising since I didn't take it by reference:
private function scale_image_dimensions(Dimensions $dimensions, Dimensions $max_size) {
if( $dimensions->width > $max_size->width ) {
$dimensions->height = $dimensions->height / ($dimensions->width / $max_size->width);
$dimensions->width = $max_size->width;
}
if( $dimensions->height > $max_size->height ) {
$dimensions->width = $dimensions->width / ($dimensions->height / $max_size->height);
$dimensions->height = $max_size->height;
}
return $dimensions;
}
How do I specify that I want the function to make a copy of the objects passed into it, and then return one of them?
update
It seems something else is fishy -- I changed the argument from $dimensions
to $adimensions
, and put $dimensions = $adimensions
at the beginning of the function.
But the caller's variable still gets modified! Does assignment work by reference also? I mean... There's non way to make an assignment operator overload, or a copy constructor so... what do I do? If I want a copy I have to explicitly initialize one every time?