How to use php classes between other classes

I know the basics of PHP and have only ever used it to debug Wordpress code generally but now I want to write my own little program to download an email and process an attachment and I have decided to try using classes as I have a basic understanding of OO programming.

SO PLEASE READ: I am a novice! I have a slim grasp of OOP

My issue is that I have created a function called printStatus() so I can toggle on/off output of comments. I was looking at this and I’m not sure how or if it would fit into a class structure or if I need to include this function in every other class I create?

Basically - If I created a class, I would need to make it available to all other classes (i.e. a global class) but I’m not sure if that is achievable.

My Question’s are:

  1. Do I have to pass a reference to the printOutput class to and from every class I use to have it available to me OR can I declare it globally to make it available to all classes OR do I need to include the same function in every class I create?
  2. I’ve created a MySQL Connection class and I am passing that into each object for use - should (can I) declare it globally and just make it available to all classes?

Thanks for the 101.

Here is my code, am I going down the right path?: (see specifically, references to printStatus())

PS - $formatoutput->printStatus() does not work within other classes - I’m looking to understand what structure is required to make it work.

class.formatoutput.php:


    class formatOutput {
    	
    	var $debug = true;
    	
    	function printStatus($text, $html = true) {
    		
    		if ($debug) {
    			echo $text;
    			echo $html?"<br/>\
":"\
";
    		}
    	}
    	
    	function printObjectStatus($object, $html = true) {

    		if ($debug) {
    			echo '<pre>';
    			echo $text;
    			echo $html?"</pre><br/>\
":"</pre>\
";
    		}	
    	}
    }

class.connection.php:


    class Connection
    {
    	var $db_host = "host";
    	var $db_name = "name";
    	var $db_user = "user";
    	var $db_pass = "pass";
    	var $db_conn;

        function connectToDatabase() {

            $db_conn = mysqli_connect($this->db_host, $this->db_user, $this->db_pass, $this->db_name);

            if (!$db_conn) {
                die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
            }
            else
            {
                $this->db_conn = $db_conn;
                $formatoutput->printStatus( "Connection established");
            }
            return $this->db_conn;

        }

        function closeConnection() {
            mysqli_close($this->db_conn);
            $formatoutput->printStatus( "Connection closed");
        }

    }

class.customer.php:


    class Customer {

    	var $customer_id;
    	var $customer_name;


    	function getCustomer($connection, $user_id) {

    		$query = "SELECT id, name FROM customer WHERE user_id=$user_id";
    		
    		$result = mysqli_query($connection, $query);
    		
    		if($result === FALSE) {
    			die('Connect Error (' . mysqli_errno() . ') ' . mysqli_error());
    		}

    		$row_count = mysqli_field_count($connection);
    		$formatoutput->printStatus( "COUNT: (".$count.")");

    	}

    }

index.php:


    include 'class.formatoutput.php';
    include 'class.connection.php';
    include 'class.customer.php';

    $formatoutput = new formatOutput();
    $formatoutput->printStatus('Start new Connection()');
    $connection = new Connection();
    $connection->connectToDatabase();
    $customer = new Customer();
    $customer->getCustomer($connection->db_conn, "1");
    $connection->closeConnection();

I would advise you to start here http://www.php.net/manual/en/language.oop5.inheritance.php

Read that, tried that, didn’t work… That’s why I took the time to write a carefully constructed question in the hope that someone could provide guidance as opposed to a link to a manual

I won’t cover all of PHP’s OOP aspects here, please learn more in PHP website as suggested above, but to point some of them related to your code:

Variable in a class is called “property”, you need to use $this->property to access class property (there are another way to access it, depends on your needs, like self :: property). So, in one of your class:


    class formatOutput {

        var $debug = true;

        function printStatus($text, $html = true) {

            if ($debug) {
                echo $text;
                echo $html?"<br/>\
":"\
";
            }
        }
       ...

To access $debug property you need to write $this->debug.

Another thing, you write your PHP code in dinosaur era :smiley: no offence, it’s PHP 4 style (it should be extinct soon), we’re all using PHP 5 now. For a start, please use property and method visibility keyword (public, protected, private).

Ok, back to the problem:
You declared $formatOutput in global scope, so you won’t be able to access it in a function or class method. To be able to access it:

  • declare global $formatOutput in the function/method (not favorable, it’s dinosaur style too)

  • or instantiate the formatOutput class directly in the method


class Customer {

        public function getCustomer($connection, $user_id)
        {

            ...
            $output = new formatOutput();
            $output->printStatus( "COUNT: (".$count.")");

        }

    }

  • or better instantiate it in the constructor and keep it as class property

class Customer {
       protected $output;
       protected $connection;

       public function __construct()
       {
           $this->output = new formatOutput();
           $this->connection = new Connection();
       }

       public function getCustomer($user_id)
       {
            ...
            $this->output->printStatus( "COUNT: (".$count.")");
        }

       // so you can use in another method as well
       public function listCustomer()
       {
            $query = "SELECT id, name FROM customer";

            $result = mysqli_query($this->connection, $query);

            $this->output->printStatus('Whatever');
        }
}

  • or even better, pass the object to the constructor (new trend, it’s called Dependency Injection, I don’t even know why everyone is using DI now :blush:)

class Customer {
       protected $output;
       protected $connection;

       public function __construct(ConnectionInterface $connection, formatOutputInterface $formatOutput)
       {
           $this->output = $formatOutput;
           $this->connection = $connection;
       }

       public function listCustomer()
       {
            $query = "SELECT id, name FROM customer";

            $result = mysqli_query($this->connection, $query);

            $this->output->printStatus('Whatever');
       }
}

  • or even even better, use Service, Factory design pattern? don’t worry, let’s learn the basic first :wink:

What do you mean by global class? PHP’s classes are available everywhere so long as they are loaded, all you will need is to find a way to load them properly. For simple applications just include/require them at the beginning of your other class files, for more complex applications you probably want to use PHP’s class autoloader. Search for spl_autoload_register() and its the way to go.