Solved

explain this code and static values

Posted on 2013-11-18
6
280 Views
Last Modified: 2013-11-22
<?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
Comment
Question by:rgb192
  • 2
  • 2
  • 2
6 Comments
 
LVL 34

Expert Comment

by:gr8gonzo
ID: 39656692
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
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39656728
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
 

Author Comment

by:rgb192
ID: 39661462
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
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 109

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 39662189
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
 
LVL 34

Assisted Solution

by:gr8gonzo
gr8gonzo earned 250 total points
ID: 39663752
...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
 

Author Closing Comment

by:rgb192
ID: 39669152
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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question