Solved

explain this code and static values

Posted on 2013-11-18
6
273 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 108

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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 108

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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

758 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now