BitValentine
BitValentine

Reputation: 78

Passing an include file from a function in a function

I'm pretty new to classes and struggling to connect a simple function to another function. Whenever I add an echo 'test' inside the ConnectDB function it passes through the 'test'. However, it doesn't include the include files.

It's probably a noob mistake.

Note: When I copy/paste the content from ConnectDB to the UpdateFollowers function it works. I'm looking for a way to save time without using an include file.

class UpdateAccountInfo {


public function ConnectDB() {

        if (strposa($_SESSION['geturl'], $_SESSION['folders']) != FALSE) {
            include '../_includes/config.php';
            include '../_includes/opendb.php';
        } else {
            include './_includes/config.php';
            include './_includes/opendb.php';
        }   


}

// update followers
public function UpdateFollowers($getid) {

        $this->ConnectDB();

        //find the source of the ig account 
        $sql = "SELECT * FROM ig_accounts WHERE iid = $getid";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            $igname = $row["igname"];
        }
............

Upvotes: 0

Views: 72

Answers (1)

William Perron
William Perron

Reputation: 1398

What is a class?

Before going into any explanation concerning the case at hand, I think it's important to get some OOP concepts straight first. From the example in the question, I get the feeling that your understanding of classes is that they simply are "function buckets" so to speak. This isn't the case. A class is a generic data structure you can use to define objects, behavior related to those objects and data used by those objects.

class Human {

    private $firstName;
    private $lastName;
    private $dateOfBirth;

    public function __construct($fn, $ln, $dob) {
        $this->firstName = $fn;
        $this->lastName = $ln;
        $this->dateOfBirth = $dob;
    }

    public function getFullName() {
        return $this->firstName.' '.$this->lastName;
    }
}

In the example above, we've defined a basic structure shared by all objects of type Human as well as encapsulated some very basic functionalities (getting the full name of our Human).

If we take a look at your example, UpdateAccountInfo is more of a functionality rather than an object. It is a process that will always be performed by some other component of the system, for the purpose of this example let's call that other component an Account.

class Account {

    private $id;
    private $name;
    private $conn;  // <-- our DB connection
    /* other Account properties */

    public function __construct($id, $name) {
        $this->id = $id;
        $this->name = $name;
        /* Initialize DB connection */
    }

    public function updateFollowers() {
        /* Perform any logic required to update the followers */
    }
}

Now we have an object of type Account to which we add however many functions we need in the future. addFollowers(), removeFollowers(), changeUsername(). Those are all examples of processes that belong to the Account object and will likely never be used by any other component of the system.

Initializing the Database connection

You may have noticed that I have left out the database initialization part out of the previous example. There is a few reasons for this but mainly:

  1. Opening and closing a connection each time create an instance of Account (or any object for that matter) using the new keyword is very costly.
  2. It breaks the Single Responsibility Principle. I won't get into that too much as it is a pretty lengthy topic. What you need to know for the time being is that it essentially means that an object should only deal with its own data/processes, and no more. In this case, opening a database connection simply isn't the job of Account.

To get around this, we can simply encapsulate the database connection logic in a Database object.

class Database {

    private $connection;

    public function connect($localhost, $name, $password, $database) {
        $this->connection = new mysqli($localhost, $name, $password, $database);
        if($this->connection->connect_error) {
            /* throw an exception */
        }
    }

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

Now you simply need to initialize the database connection once at the beginning of the script, and pass it around to other objects/functions that may need it.

<?php
    include_once('../../config.php');
    /* include any other required files */
    $database = new Database($config['localhost'], $config['username'], $config['password'], $config['dbname']);

    // get a specific account
    $account = new Account(/* ... */, $database);

    // update the account's followers
    $account->updateFollowers(/* ... */);

If we want to modify a second account, we can do so using the same database connection we just opened.

<?php
    /* ... code from previous example ... */
    // initialize a new Account with the same Database
    $otherAccount = new Account(/* new account's info */, $database);
    $otherAccount->updateFollowers(/* ... */);

Further readings

  1. PHP documentation on OOP
  2. Wikipedia page on Single Responsibility Principle
  3. How to initialize a database connection

Upvotes: 1

Related Questions