Simple Miles to Km converter using MVC


I am trying to understand the MVC, so i decided to go right back to PHP basics and create a simply miles to km converter.

I have a Models folder, a Views folder and then an index.php file in the source files.

In the Models folder i have a file called “class.converter.php” shown below:-

class Converter {
    var $number = 0, $unit = '';

    public function  __construct($number, $unit) {
    $this->number = $number;
    $this->unit = $unit;

    public function convert() {
        if (is_numeric($this->number)) {
            if ($this->unit == 'miles to km'){
                $result = $this->number * 1.609;
            } elseif ($this->unit == 'km to miles'){
                $result = $this->number * 0.621;
            } else {
                $result = 'error';
        } else {
            $result = false;
        return $result;

Then in Views i have “index.phtml” shown below:-

        <?php echo '<?xml version="1.0" encoding="UTF-8"?>';?>
        <div style="background: #c0c0c0; padding: 10px">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
                    <td><label>Convert: </label></td>
                    <td><input type="text" name="name" value="<? echo $_POST['number'] ?>"></td>
                    <td><label>From: </label></td>
                        <select name="unit">
                            <option>km to miles</option>
                            <option>miles to km</option>
                    <td><input type="submit" name="submit" value="submit"></td>
        <?php if(isset($view->result)) : ?>
        <p><?php echo $view->result; ?></p>
        <?php endif; ?>

Finally index.php file is as follows, this is located in the source files outside the Model and Views folders:-


require_once ('Models/class.converter.php');

if(isset ($_POST['submit'])){
    $converter = new Converter($_POST['number'], $_POST['unit']);
        $view->result = 'Not a valid number.';
    } else {
    $value = $converter->convert();
    $view->result = 'Converting ' . $_POST['number'] . ' from '
            . $_POST['unit'] . ' is ' . $value . '.';

require_once ('Views/index.phtml');

Now i am running this locally, so i cant show you what i am getting. But I cant seem to echo the result. Whichever input i out in i get “Not a valid number.”…

Can anyone help me with this very simple exercise?



Your mistake should be obvious then.


– $result doesn’t exist.
Also, the converter is not a model. Model = database tables.

Thanks guys,

The error reporting led me to the answer, which was that $result did not exist, i forgot to declare the variable!


Model can also be some other data source like xml file but yeah, 1 model usually = 1 db table.