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

Returning PHP Objects

This tutorial will use a simple example regarding how to return methods and objects from a class. Although the code is not optimal for production use, it does demonstrate a process for which the class is instantiated, and a database object is used for database queries.

Here is a summary of what is going on. The line below instantiates a new instance of the MyObject class. Since the constructor is triggered first, it runs the $this->set_connection() method.

When that method runs, it makes the property $this->connection to take on the returned value from the PDO_Connect() method.

Thus, the $PDO->connection is used to access the database. For code readability, you would likely just make a simpler connection, like that shown in the page https://fullstackwebstudio.com/locations/coding-blog/pdo-database-connection.html

In addition to the above, you can also access the the database variable using the get_connection() method and that example is at the end of the file.

class MyObjects
{

    public $var1 = "test";
    private $var2 = "test2";
    protected $var3 = "test3";
    public $connection;
    public $PDO;

    function __construct()
    {
        $this->set_connection();

    }

    function PDO_Connect()
    {
        $user = 'root';
        $pass = '';
        $PDO = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
        $PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
        return $PDO;
    }


    public function set_connection()
    {
        $this->connection = $this->PDO_Connect();
    }

    public function get_connection()
    {
        return $this->connection;
    }

}


$PDO = new MyObjects();
print_r($PDO);
echo "<br/><br/>";
echo "Var1: $PDO->var1";
echo "<br/><br/>";
//var_dump($PDO->connection); //object(PDO)#2 (0) { }
//echo "<br/><br/>";
$PDO = $PDO->connection;

$command = "SELECT * FROM leads";
$result = $PDO->prepare($command);
$result->execute();

echo "<strong>Method A</strong>";

echo "<ol>";

while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    echo "<li>Name: {$row['firstname']} - {$row['lastname']}</li>";
}
echo "</ol>";

echo "<strong>Method B</strong>";

$test = new MyObjects();
$db = $test->get_connection();

$command = "SELECT * FROM leads";
$result = $db->prepare($command);
$result->execute();

echo "<ol>";

while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    echo "<li>Name: {$row['firstname']} - {$row['lastname']}</li>";
}
echo "</ol>";