Passing arguments to an object's method

I thought I couldn’t see an object being created. So you create the class just to be able to use the method within it? Why is that better than simply creating a simple function and calling that? (please be aware - I am new to this OOP business)

E.g. because for some functionality you will need not single function, but a lot of them. This functionality could be modifyed and suddenly will need a some data to save. If this is class, you can add properties there. Etc…

2 Likes

Adding onto this, you don’t necessarily want everything to be public. You don’t want people modifying things where it really shouldn’t be. That’s why using OOP is a lot better. Because you can restrict a developer on how they use those objects and methods.

Creating just a standalone function is ok, but you lose the ability to apply the 4 principles of OOP to your code structure.

1 Like

Is that these four? Wheen I Googled I was offered three, four and five principles of OOP!

So in this scernario, if I then want to calculate the area of the room in metric and in imperial, what would be the best way to proceed? Would I add two more methods to the

class DistanceConverter

and call them in the same way?

I wouldn’t use the DistanceConverter for that, as that is just for converting distances (hence the name) and shouldn’t have anything to do with how Rooms work.

I think I would do it like this:

class Room {
    public function __construct(private float $width, private float $length, private string $roomName) {
    }

     public function getWidth(): float {
        return $this->width;
    }

    public function getLength(): float {
        return $this->length;
    }

    public function getArea(): float {
        return $this->width * $this->length;
    }
}


$room = new Room(12, 18, 'Some room');
echo 'The area of the room is ', $room->getArea(), ' (or ', DistanceConverter::convertMetricToImperial($room->getArea()), ')';

This is based on the Single Responsibility Principle - an object should be responsible for one thing and one thing only. I.e. the `Room` should not be responsible for metric to imperial conversion, the `DistanceConverter` should not be concerned with calculating the area of a `Room`.
The `Room` class should know everything about the `Room`, nothing else. The `DistanceConverter` should know everything about converting distances, nothing else.
2 Likes

Yes

It isn’t. It’s a different way of doing the same thing. Most people like static methods on a class over functions because that way you group similar functions in one class, and possible add some private methods to the class to help with stuff, and maybe even static properties, but you really need to watch out with those, as they are basically just global variables. And global variables make everything hard.

2 Likes

think that might have some issue with not knowing the units, but the point stands :wink:

I… disagree, but it somewhat depends on how we’re defining ‘simple function’. Assuming OP means outside of the class, it avoids having to name things in odd ways to avoid name collisions in the global function space.

$circle->getArea();
$square->getArea();

vs

getCircleArea($circle);
getSquareArea($square);

(I am aware that this is where the idea of extension and inheritance becomes relevant, but for the sake of simplicity, assume $circle and $square are not related.)

1 Like

Just a little disclaimer that this is sort of going off-topic and not really solving the original problem. But the 4 principles are

  • Inheritance
  • Abstraction
  • Encapsulation
  • Polymorphism
1 Like

Wouldn’t that give an incorrect result because the conversion factor is for a linear measurement rather than area - the conversion factor would need to be squared.
Unless I have misunderstood.

The way convertMetricToImperial was written, it was written to translate Meters into Feet and Inches. It was, perhaps, not accurately named.

You would need a function that either took in units, or to write a different function to give you a square-meter-to-square-feet conversion. (Not that that’s relevant to the actual subject of OOP, but for the practical application.)

2 Likes

Eventually got the internet back on so can now reply :wink:

@rpkamp,
Your examples clarified the passing of a Class as a method parameter and also the use of Static Methods. Very good and far better than previous explanations. Thanks.

While the Internet was off I also solved an accordion problem and also requiring numerous files to make the following:

Online Examples

1 Like

I wasn’t talking about the getArea method, but rather about the DistanceConverter::convertMetricToImperial static method. Obviously non-static methods on an object and regular functions are completely different. No debate on that :slight_smile:

Ah right, I simplified it too much.

So maybe introduce an AreaConverter?

class AreaConverter {
    public function convertMetricToImperial(float $squareMeters): float {
        return 10.764 * $squareMeters;
    }
}

Or rename the DistanceConverter and add this method there too.

2 Likes

I first attended an Object-Orientated Programming lecture at a Manchester UK Computer Club way back when I was using one of Nantucket Corporation’s Clipper Seasonal Versions for their DBase Compilers… I still cannot think in terms of Classes and unfortunately still treat them as glorified PHP function libraries… but I am making a little progress :slight_smile:

2 Likes

When I try to run that I get:

Parse error : syntax error, unexpected ‘private’ (T_PRIVATE), expecting variable (T_VARIABLE) in C:\Program Files\Ampps\www\convertOOP\convert02.php on line 3

I put <?php in a line above so line 3 is:

public function __construct(private float $width, private float $length, private string $roomName) {

Sounds like you’re not running PHP 8 then. Try this:

class Room {
    private float $width;
    private float $length;
    private string $roomName;

    public function __construct(float $width, float $length, string $roomName) {
        $this->width = $width;
        $this->length = $length;
        $this->roomName = $roomName;
    }

     public function getWidth(): float {
        return $this->width;
    }

    public function getLength(): float {
        return $this->length;
    }

    public function getArea(): float {
        return $this->width * $this->length;
    }
}

Parse error : syntax error, unexpected ‘float’ (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in C:\Program Files\Ampps\www\convertOOP\convert02.php on line 2

(This time I put <?php on the same line as the first line of your code.)
I am running PHP 7.3, on AMPPS

<?php class Room {
    private  $width;
    private  $length;
    private  $roomName;

    public function __construct(float $width, float $length, string $roomName) {
        $this->width = $width;
        $this->length = $length;
        $this->roomName = $roomName;
    }

     public function getWidth(): float {
        return $this->width;
    }

    public function getLength(): float {
        return $this->length;
    }

    public function getArea(): float {
        return $this->width * $this->length;
    }
}
?>

gives no errors

<?php 
    class Room {
    private  $width;
    private  $length;
    private  $roomName;

    public function __construct(float $width, float $length, string $roomName) {
        $this->width = $width;
        $this->length = $length;
        $this->roomName = $roomName;
    }

     public function getWidth(): float {
        return $this->width;
    }

    public function getLength(): float {
        return $this->length;
    }

    public function getArea(): float {
        return $this->width * $this->length;
    }
      
}

class DistanceConverter {
    public static function convertMetricToImperial(float $x): string {
        $valInFeet = $x * 3.2808399;
        $valFeet = (int) $valInFeet;
        $valInches = round(($valInFeet-$valFeet) * 12);

        return $valFeet 
            ."&prime; " 
            .$valInches
            ."&Prime;" ;
    }
}

$room = new Room(12, 18, 'Some room');

echo 'The room is ' . DistanceConverter::convertMetricToImperial($room->getLength()) . ' by ' . DistanceConverter::convertMetricToImperial($room->getWidth());
?>

outputs:

The room is 59′ 1″ by 39′ 4″

  1. Make DistanceConverter::convertMetricToImperial() non-static. At all, static class members is some special case. Normally developer should to avoid it.

  2. Instance of DistanceConverter should be a property of Room. And Room should have methods, that return converted data with help of DistanceConverter.