Site Cloner PHP Script
Bargain Hunter PHP Script
Job Hunter PHP Script
Site Login and Access Control PHP Script

Returning Values With PHP OOP

When you use classes and OOP, you have various ways to return values. Asides from using OOP, you can also call functions and execute them without object scope.

With the Form class below, the values returned are ‘added’, ‘test2’, ‘gedit’, ‘test2’ and ‘apple’.

The first value ‘added’ was passed into the be() method and echoed within the function. The second value ‘test2’ was returned from the be() method. Both of these values are delivered from the code echo $test->be(‘added’); 

The third value ‘gedit’ came about from the set_var() and get_var() methods. The line echo “<br/>New Value: ” . $test2->get_var(); caused it to be printed.

The fourth value ‘test2’ came about by using the instance name and its property name. Thus, $this->b used within the class can be output as $test2->b from outside the class; as long as there is an instance $test2. The $test2 instance was instantiated with $test2 = new Form();

Finally, ‘apple’ was printed using Form::be(‘apple’); If you look at the image, you will see a warning because this method has no object scope; thus return $this->b; does nothing. From a procedural programmers point of view, using the scope resultion operation is similar to using a regular procedural PHP function. Note, if you comment Form::be(‘apple’); you will see that you can return a variable from the class just as you would with procedural PHP. The line $procedural = Form::be_procedural(‘orange’); will return the variable.

class Tag {

    public $aa = "";
    public $bb = "";
    public $dd = "";

   }

class Form extends Tag {

    public $a = "test";
    public $b = "test2";
    public $d = "testd";

    public function be($c) {
        echo $c . "<br/>";
        return $this->b;      
    }

    public function be_procedural($c) {
        echo $c . "<br/>";
        return $c;      
    }
        
    public function set_var($value) {
        $this->new_value = $value;
    }

    public function get_var() {
        return $this->new_value;
    }
   
}

$test = new Form('one', 'two');

echo $test->be('added'); 
echo "<hr>";


$test2 = new Form();
$test2->set_var('gedit');
echo "<br/>New Value: " . $test2->get_var();
echo "<br/>B Function: ". $test2->b."<br/>";
?>
<hr>
<?php
//NO OBJECT SCOPE
Form::be('apple'); 
$procedural = Form::be_procedural('orange');
echo $procedural;
?>

Browser Output