Avatar of rgb192
rgb192
Flag for United States of America asked on

explain this code and static values

<?php

$originalValue = "5'10\"";
echo "{$originalValue} = " . Converter::ToInches($originalValue) . " total inches!\n";

$originalValue = "female";
echo "{$originalValue} = " . Converter::ToInches($originalValue) . " total inches!\n";


class Converter
{
  public static function ToInches($original)
  {
    if(preg_match("/^(\d+)'(\d+)\"/",$original,$matches))
    {
          $feet = intval($matches[1]);
          $inches = intval($matches[2]);
          return ($feet * 12) + $inches;
    }
    else
    {
          throw new Exception("I don't understand the value {$original}!");
    }
  }
}

Open in new window


Please explain the reason why this code works

I am learning about object oriented program and static values.

Why is a static value best for this requirement?
PHP

Avatar of undefined
Last Comment
rgb192

8/22/2022 - Mon
gr8gonzo

Static values and functions mean that they are not tied to an instance of the class. It means you can use those values and functions without an instance.

For example, let's think of shapes. All squares are rectangles - they simply have the same height and width, but rectangles all have some common properties that don't usually change. Look at this definition:

class Rectangle
{
   public static $NumberOfSides = 4;
   public $Height;
   public $Width;
}

Because ALL rectangles, no matter what size they are, all have 4 sides, we can make that a static value. That value becomes attached to the TYPE of the class.

We can also have several types of rectangles, though, each with their own sizes:

$Square = new Rectangle();
$Square->Height = 10;
$Square->Width = 10;

$TallBox = new Rectangle();
$TallBox->Height = 100;
$TallBox->Width = 10;

$WideBox = new Rectangle();
$WideBox->Height = 10;
$WideBox->Width = 100;

So there you have 3 INSTANCES of the Rectangle class, each with their own height and width. If you wanted to get the number of sides for any box, you wouldn't need any of those instances. You could just do:

echo Rectangle::$NumberOfSides; // 4

So in my original example, I used a static method because unit conversion is usually just a utility type of situation where you don't have lots of per-instance properties that you need to hang onto - you just pass in a value and get a value back.

You could change it to an instance (non-static) method by changing the function call...

OLD:
public static function ToInches($original)

NEW:
public function ToInches($original)

... but if you do that, then in order to use the ToInches function, you have to instantiate the class:

$originalValue = "5'10\"";
$x = new Converter();
echo $x->ToInches($originalValue);

So there is some memory overhead with objects / class instances and in this case, there's no benefit to having an instance because there are no per-instance properties for conversion.
Ray Paseur

Static does not appear to be necessary in this example.  Nothing wrong with it, but there is nothing necessarily "static" in the nature of the function (method).
http://php.net/manual/en/language.oop5.static.php

A static function (method) cannot use $this .  If a non-static method is called statically, you'll get something like this (assuming you're using STRICT error reporting).  Notwithstanding the message, the non-static method will still work correctly.
Strict Standards: Non-static method Converter::ToInches() should not be called statically in /path/to/RAY_temp_rgb192.php on line 4

A static method call is done in this line with the double-colon between the class name and the method name:

Converter::ToInches($originalValue)

An alternative approach would be to create a new object instance of the Converter and feed it the heights, returning the inches or an error message.

<?php

// INSTANTIATE THE CONVERTER
$conv = new Converter;

$originalValue = "5'10\"";
echo "{$originalValue} = " . $conv->ToInches($originalValue) . " total inches!\n";

$originalValue = "female";
echo "{$originalValue} = " . $conv->ToInches($originalValue) . " total inches!\n";


class Converter
{
    public function ToInches($original)
    {
        if(preg_match("/^(\d+)'(\d+)\"/",$original,$matches))
        {
            $feet = intval($matches[1]);
            $inches = intval($matches[2]);
            return ($feet * 12) + $inches;
        }
        else
        {
            return "I don't understand the value {$original}!";
        }
    }
}

Open in new window

HTH, ~Ray
rgb192

ASKER
I understand that all rectangles has 4 sides which is static
but do all rectangles have inches?

In both code samples, why are there no properties in the class, before the method ToInches()
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER CERTIFIED SOLUTION
Ray Paseur

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
gr8gonzo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
rgb192

ASKER
Thank you both for clarifying concepts.

Think of a static method as a piece of functionality you can "borrow" and reuse -- much like a function definition in non-OOP code.


For example, if we multiplied by the number 12 in a hundred different spots in the code, it would make the code more readable to use a variable or property instead of the number 12.