Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 290
  • Last Modified:

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?
0
rgb192
Asked:
rgb192
  • 2
  • 2
  • 2
2 Solutions
 
gr8gonzoConsultantCommented:
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.
0
 
Ray PaseurCommented:
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
0
 
rgb192Author Commented:
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()
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
Ray PaseurCommented:
Not sure I understand how to answer the question about rectangles, but I'll take a run at the other part.  

A static method cannot use $this. In other words, it cannot create or alter object properties.  And in the Converter class, there is no data that needs to be stored in the object -- it receives its input and returns its output by using local variables only.  You would only need to use $this if more than one method in the class needed access to a data element, and if that were the case, you would need an object instance of the class, so you would not use static.

Think of a static method as a piece of functionality you can "borrow" and reuse -- much like a function definition in non-OOP code.
0
 
gr8gonzoConsultantCommented:
...but do all rectangles have inches?

I think you are mixing up the examples. The rectangles example was just to illustrate static properties versus an instance property.

...why are there no properties in the class, before the method ToInches()
There wasn't really a need for them, but you -could- add properties if you wanted.

For example, you could always store the number 12 (number of inches in a foot) into a property, and then use that value from the method instead of just hardcoding 12, but since there are ALWAYS 12 inches in a foot, and that specific function is always doing the feet-to-inches conversion, it didn't make sense to make that a property.

I typically only make things properties whenever they could change or if it would make the code easier to read. 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. Or if you were trying to calculate a tax rate, which could change sometimes, it would make sense to put that value in a property.
0
 
rgb192Author Commented:
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.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 2
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now