Hallo,

Gister weer begonnen met OOP en ik had gister een login/register/passforget systeem gemaakt met OOP en ik vroeg mij af of ik het zo ongeveer goed deed en wat ik kan verbeteren.

De database users ziet er zo uit:


databaseClass.php

<?php
    class Database
    {
        private $servername;
        private $username;
        private $password;
        private $database;
        private $conn;

        protected function connect()
        {
            if ($this->conn == NULL)
            {
                $this->servername = 'localhost';
                $this->username = 'root';
                $this->password = '';
                $this->database = 'oop';

                $this->conn = new mysqli($this->servername, $this->username, $this->password, $this->database);
            }
            
            return $this->conn;
        }
    }
?>


userClass.php

<?php
    class User extends Database
    {
        protected function generateRandomCode($length)
        {
            $unique = false;

            while (!$unique)
            {
                $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                $charactersLength = strlen($characters);
                $randomCode = '';

                for ($i = 0; $i < $length; $i++)
                {
                    $randomCode .= $characters[rand(0, $charactersLength - 1)];
                }

                $sql = "SELECT `pcode` FROM `users` WHERE `change_ww_code` = '" . $this->connect()->real_escape_string($randomCode) . "'";
                $query = $this->connect()->query($sql);

                if ($query || $query->num_rows == 0)
                {
                    $unique = true;
                }
            }

            if ($unique == true)
            {
                return $randomCode;
            }
        }

        public function login($username, $password)
        {
            $sql = "SELECT `username`, `password`, `active` FROM `users` WHERE `username` = '" . $this->connect()->real_escape_string($username) . "'";
            $query = $this->connect()->query($sql);

            if ($query->num_rows == 0)
            {
                throw new Exception("De inlog gegevens zijn onjuist.");
            }
            else
            {
                $data = $query->fetch_assoc();

                if ($data['active'] == 0)
                {
                    throw new Exception("Je account is gedeactiveerd, neem contact op met een administrator.");
                }
                elseif (password_verify($password, $data['password']) == true)
                {
                    $sql = "UPDATE `users` SET `password` = '" . password_hash($password, PASSWORD_BCRYPT) . "', `last_online` = '" . date('Y-m-d H:i:s') . "', `change_ww_code` = '', `change_ww_perm` = '0' WHERE `username` = '" . $this->connect()->real_escape_string($username) . "'";
                    $query = $this->connect()->query($sql);
                }
                else
                {
                    throw new Exception("De inlog gegevens zijn onjuist.");
                }
            }
        }

        public function register($username, $password, $passwordrepeat)
        {
            $sql = "SELECT `username`, `password` FROM `users` WHERE `username` = '" . $this->connect()->real_escape_string($username) . "'";
            $query = $this->connect()->query($sql);

            if ($query->num_rows == 1)
            {
                throw new Exception("De gebruikersnaam is ongeldig.");
            }
            elseif ($password != $passwordrepeat || strlen($password) <= 5)
            {
                throw new Exception("Controleer de wachtwoorden of ze overeenkomen en 6 tekens of langer zijn.");
            }
            else
            {
                $sql = "INSERT INTO `users` (`username`, `password`, `register_date`) VALUE ('" . $this->connect()->real_escape_string($username) . "', '" . password_hash($password, PASSWORD_BCRYPT) . "', '" . date('Y-m-d H:i:s') . "')";
                $query = $this->connect()->query($sql);
                if (!$query)
                {
                    throw new Exception("Er is iets fout gegaan, neem contact op met een administrator.");
                }
            }
        }

        public function passForget($username, $password, $passwordrepeat, $code)
        {
            $sql = "SELECT `username`, `change_ww_perm`, `change_ww_code` FROM `users` WHERE `username` = '" . $this->connect()->real_escape_string($username) . "'";
            $query = $this->connect()->query($sql);

            if ($query->num_rows == 0)
            {
                throw new Exception("De gebruikersnaam is ongeldig.");
            }
            else
            {
                $data = $query->fetch_assoc();
                if ($password != $passwordrepeat || strlen($password) <= 5)
                {
                    throw new Exception("Controleer de wachtwoorden of ze overeenkomen en 6 tekens of langer zijn.");
                }
                elseif ($data['change_ww_perm'] == 0)
                {
                    throw new Exception("Je hebt geen toestemming om je wachtwoord te veranderen.");
                }
                elseif (!isset($code) || $code != $data['change_ww_code'])
                {
                    throw new Exception("De opgegeven code is onjuist.");
                }
                else
                {
                    $sql = "UPDATE `users` SET `password` = '" . password_hash($password, PASSWORD_BCRYPT) . "', `change_ww_perm` = '', `change_ww_code` = '' WHERE `username` = '" . $this->connect()->real_escape_string($username) . "'";
                    $query = $this->connect()->query($sql);
                    if (!$query)
                    {
                        throw new Exception("Er is iets fout gegaan, neem contact op met een administrator.");
                    }
                }
            }
        }
    }
?>


Ik weet niet of ik teveel if/elseif/else statements heb zo ja, zouden jullie mij dan kunnen vertellen hoe ik dit kan verbeteren :)

Graag hoor ik verbeter punten.

Mvg,
Rob
Dit had ik al eens eerder gemaakt, werkte prima.

function getValue($key, $return = false)
	{
		$lines_array = file($_SERVER['DOCUMENT_ROOT'] . '/Workspace/Novara Bank/paneel/assets/text.txt');

		foreach ($lines_array as $line)
		{
			$values = explode(': ', $line);

			if (trim($values[0]) == $key)
			{
				if ($return == true)
				{
					return $values[1];
				}
				else
				{
					echo $values[1];
				}
			}
		}
	}

if (isset($_POST['type']))
	{
		if ($_POST['type'] == 'login')
		{
			$searchUserSql = $mysqli->query(
										    "SELECT *
											FROM `leden`
											WHERE `gebruikersnaam` = '" . save_string($_POST['username']) . "'
											ORDER BY `id`
											DESC
											LIMIT 1"
										   );

			if (
				!$searchUserSql
				|| $searchUserSql->num_rows == 0
			   )
			{
				getValue('wrong_login');
			}
			else
			{
				$userDetails = $searchUserSql->fetch_assoc();

				if (!password_verify($_POST['password'], $userDetails['wachtwoord']))
				{
					getValue('wrong_login');
				}
				elseif ($userDetails['actief'] === 0)
				{
					getValue('inactive_login');
				}
				else
				{
					if (createNewLog('heeft zichzelf ingelogd', $userDetails['id']) == false)
					{
						getValue('error');
					}
					else
					{
						$updateUserDetailsSql = $mysqli->query(
															   "UPDATE `leden`
															   SET `wachtwoord` = '" . save_string(password_hash($_POST['password'], PASSWORD_BCRYPT)) . "',
															   `laatst_online` = '" . save_string(date('H:i:s d-m-Y', time())) .  "'"
															  );
						if (!$updateUserDetailsSql)
						{
							getValue('error');
						}
						else
						{
							$_SESSION['gebruikerInfo'] = $userDetails;
							$_SESSION['gebruikerInfo']['wachtwoord'] = '';
							getValue('success_login');
						}
					}
				}
			}
		}

$(".form-l-submit").click(function() {
                    var username = $(".form-l-username").val();
                    var password = $(".form-l-password").val();
                    var dataString = 'username=' + username + '&password=' + password + '&type=login';

                    if (!username.trim() || !password.trim()) {
                        $('.message').addClass('callout callout-danger');
                        $('.message').html('Je hebt niet alle velden ingevuld.');
                        setTimeout(function() {
                            $('.message').removeClass('callout callout-danger');
                            $('.message').html('');
                        }, 5000);
                    } else {
                        $.ajax({
                            type: "POST",
                            url: "/Workspace/Novara Bank/paneel/includes/actions.php",
                            data: dataString,
                            cache: false,
                            success: function(result) {
                                if (result.includes("Je bent met succes ingelogd.") == true) {
                                    location.reload();
                                }
 								else
								{
									$('.message').addClass('callout callout-danger');
                                    $('.message').html(result);
                                    setTimeout(function() {
                                        $('.message').removeClass('callout callout-danger');
                                        $('.message').html('');
                                    }, 5000);
                                }
                            }
                        });
                    }
                    return false;
                });

Hier ging alles prima, maar wou verder met OOP

Los van de vorm waarin je dit giet (oop, procedureel), je bent hier meerdere dingen (inloggen, updaten van wachtwoord?!) tegelijkertijd aan het doen. Het lijkt mij belangrijk om dingen op te splitsen in verschillende acties.

Ook kan het handig zijn om dingen om te draaien (EDIT: beter gezegd: het gebruik van negaties te voorkomen als dit mogelijk is), in plaats van:
if (!C) {
  A
} else {
  B
}

Zou je ook, en wellicht beter, dit kunnen doen:
if (C) {
  B
} else {
  A
}

Of op zijn minst de ! explicieter kunnen maken, bijvoorbeeld door:
if (C === false) {
  A
} else {
  B
}

(of false === C, whatever floats your boat)

Ook staat er geen letter annotatie in je code, dus dit is ook vrij moeilijk leesbaar/interpreteerbaar door mensen die deze code niet hebben geschreven omdat het doel/de bedoeling niet is gespecificeerd.
Oké, bedankt. Wat is letter anootatie? Zijn dat comments?
De vraagstelling is natuurlijk heel algemeen: "Doe ik OOP goed?"

Ik programmeer al een jaar of dertig, en het verbetert nog elk jaar. De inzichten en technieken die als "goed" beschouwd worden veranderen ook elk jaar. Los van de hypes die langskomen, is er wel een aantal vuistregels te geven die ik je wil meegeven als je OOP wilt programmeren.

Single Responsibility Principle: hou je classes kort en je methods klein. Zorg dat een method maar 1 ding heel goed doet, en meer niet. Dit principe is onderdeel van SOLID (er zijn dus 5 principes)

Lees iets over loose coupling en depency injection.

Wees voorzichtig met child classes en inheritance. Je kunt een class beter samenstellen door hem verschillende interfaces te laten implementeren dan dat je heel veel parent en child relaties creëert. Dit principe heet "composition over inheritance".

Helden op dit gebied: Uncle Bob, Taylor Otwell, Jeffrey Way, Eric Evans.

Tot slot: OOP en Design Patterns leer je niet in een maand, daarom is het zo leuk. Je blijft steeds maar dingen bij leren.
Bedankt voor jullie reacties!

Jan Koehoorn, ik programmeer nu 1 jaar met een pauze van ongeveer 6 maanden (sinds gister begonnen weer) en ik hoop dat ik veel nog kan leren over programmeren :)
- Rob - op 26/12/2017 16:35:11
Oké, bedankt. Wat is letter anootatie? Zijn dat comments?

Ja commentaarregels of -blokken, dan kun je iig aanhalen wat de bedoeling was. Iemand anders kan dan oordelen of jouw code ook doet wat het dient te doen. Als je hier niks over opschrijft wordt dat behoorlijk lastig.

En tis ook handig als je zelf na X dagen, maanden, jaren nog eens iets terugzoekt en dan kan zien wat (eigenlijk) de bedoeling was.
Nick Vledder op 26/12/2017 15:47:14

Zou je User niet kunnen zien als een representatie van een deel van de database?

Nee, een User is niet (een onderdeel van) een database. Het is slechts inhoud die door de database wordt vastgehouden. Een chauffeur of een passagier is ook geen (onderdeel van een) auto.

Hey,

Is dit een goede database class?:


<?php
/**
 * Exception helper for the Database class
 */
class DatabaseException extends Exception
{
    // Default Exception class handles everything
}
/**
 * A basic database interface using MySQLi
 */
class Database
{
    private $sql;
    private $mysql;
    private $result;
    private $result_rows;
    private $database_name;
    private static $instance;
    /**
     * Query history
     *
     * @var array
     */
    static $queries = array();
    /**
     * Database() constructor
     *
     * @param string $database_name
     * @param string $username
     * @param string $password
     * @param string $host
     * @throws DatabaseException
     */
    function __construct($database_name, $username, $password, $host = 'localhost')
    {
        self::$instance = $this;
        $this->database_name = $database_name;
        $this->mysql = mysqli_connect($host, $username, $password, $database_name);
        if (!$this->mysql) {
            throw new DatabaseException('Database connection error: ' . mysqli_connect_error());
        }
    }
    /**
     * Get instance
     *
     * @param string $database_name
     * @param string $username
     * @param string $password
     * @param string $host
     * @return Database
     */
    final public static function instance($database_name = null, $username = null, $password = null, $host = 'localhost')
    {
        if (!isset(self::$instance)) {
            self::$instance = new Database($database_name, $username, $password, $host);
        }
        return self::$instance;
    }
    /**
     * Helper for throwing exceptions
     *
     * @param $error
     * @throws Exception
     */
    private function _error($error)
    {
        throw new DatabaseException('Database error: ' . $error);
    }
    /**
     * Turn an array into a where statement
     *
     * @param mixed $where
     * @param string $where_mode
     * @return string
     * @throws Exception
     */
    public function process_where($where, $where_mode = 'AND')
    {
        $query = '';
        if (is_array($where)) {
            $num = 0;
            $where_count = count($where);
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    $w = array_keys($v);
                    if (reset($w) != 0) {
                        throw new Exception('Can not handle associative arrays');
                    }
                    $query .= " `" . $k . "` IN (" . $this->join_array($v) . ")";
                } elseif (!is_integer($k)) {
                    $query .= ' `' . $k . "`='" . $this->escape($v) . "'";
                } else {
                    $query .= ' ' . $v;
                }
                $num++;
                if ($num != $where_count) {
                    $query .= ' ' . $where_mode;
                }
            }
        } else {
            $query .= ' ' . $where;
        }
        return $query;
    }
    /**
     * Perform a SELECT operation
     *
     * @param string $table
     * @param array $where
     * @param bool $limit
     * @param bool $order
     * @param string $where_mode
     * @param string $select_fields
     * @return Database
     * @throws DatabaseException
     */
    public function select($table, $where = array(), $limit = false, $order = false, $where_mode = "AND", $select_fields = '*')
    {
        $this->result = null;
        $this->sql = null;
        if (is_array($select_fields)) {
            $fields = '';
            foreach ($select_fields as $s) {
                $fields .= '`' . $s . '`, ';
            }
            $select_fields = rtrim($fields, ', ');
        }
        $query = 'SELECT ' . $select_fields . ' FROM `' . $table . '`';
        if (!empty($where)) {
            $query .= ' WHERE' . $this->process_where($where, $where_mode);
        }
        if ($order) {
            $query .= ' ORDER BY ' . $order;
        }
        if ($limit) {
            $query .= ' LIMIT ' . $limit;
        }
        return $this->query($query);
    }
    /**
     * Perform a query
     *
     * @param string $query
     * @return $this|Database
     * @throws Exception
     */
    public function query($query)
    {
        self::$queries[] = $query;
        $this->sql = $query;
        $this->result_rows = null;
        $this->result = mysqli_query($this->mysql, $query);
        if (mysqli_error($this->mysql) != '') {
            $this->_error(mysqli_error($this->mysql));
            $this->result = null;
            return $this;
        }
        return $this;
    }
    /**
     * Get last executed query
     *
     * @return string|null
     */
    public function sql()
    {
        return $this->sql;
    }
    /**
     * Get an array of objects with the query result
     *
     * @param string|null $key_field
     * @return array
     */
    public function result($key_field = null)
    {
        if (!$this->result_rows) {
            $this->result_rows = array();
            while ($row = mysqli_fetch_assoc($this->result)) {
                $this->result_rows[] = $row;
            }
        }
        $result = array();
        $index = 0;
        foreach ($this->result_rows as $row) {
            $key = $index;
            if (!empty($key_field) && isset($row[$key_field])) {
                $key = $row[$key_field];
            }
            $result[$key] = new stdClass();
            foreach ($row as $column => $value) {
                $this->is_serialized($value, $value);
                $result[$key]->{$column} = $this->clean($value);
            }
            $index++;
        }
        return $result;
    }
    /**
     * Get an array of arrays with the query result
     *
     * @return array
     */
    public function result_array()
    {
        if (!$this->result_rows) {
            $this->result_rows = array();
            while ($row = mysqli_fetch_assoc($this->result)) {
                $this->result_rows[] = $row;
            }
        }
        $result = array();
        $n = 0;
        foreach ($this->result_rows as $row) {
            $result[$n] = array();
            foreach ($row as $k => $v) {
                $this->is_serialized($v, $v);
                $result[$n][$k] = $this->clean($v);
            }
            $n++;
        }
        return $result;
    }
    /**
     * Get a specific row from the result as an object
     *
     * @param int $index
     * @return stdClass
     */
    public function row($index = 0)
    {
        if (!$this->result_rows) {
            $this->result_rows = array();
            while ($row = mysqli_fetch_assoc($this->result)) {
                $this->result_rows[] = $row;
            }
        }
        $num = 0;
        foreach ($this->result_rows as $column) {
            if ($num == $index) {
                $row = new stdClass();
                foreach ($column as $key => $value) {
                    $this->is_serialized($value, $value);
                    $row->{$key} = $this->clean($value);
                }
                return $row;
            }
            $num++;
        }
        return new stdClass();
    }
    /**
     * Get a specific row from the result as an array
     *
     * @param int $index
     * @return array
     */
    public function row_array($index = 0)
    {
        if (!$this->result_rows) {
            $this->result_rows = array();
            while ($row = mysqli_fetch_assoc($this->result)) {
                $this->result_rows[] = $row;
            }
        }
        $num = 0;
        foreach ($this->result_rows as $column) {
            if ($num == $index) {
                $row = array();
                foreach ($column as $key => $value) {
                    $this->is_serialized($value, $value);
                    $row[$key] = $this->clean($value);
                }
                return $row;
            }
            $num++;
        }
        return array();
    }
    /**
     * Get the number of result rows
     *
     * @return bool|int
     */
    public function count()
    {
        if ($this->result) {
            return mysqli_num_rows($this->result);
        } elseif (isset($this->result_rows)) {
            return count($this->result_rows);
        } else {
            return false;
        }
    }
    /**
     * Execute a SELECT COUNT(*) query on a table
     *
     * @param null $table
     * @param array $where
     * @param bool $limit
     * @param bool $order
     * @param string $where_mode
     * @return mixed
     */
    public function num($table = null, $where = array(), $limit = false, $order = false, $where_mode = "AND")
    {
        if (!empty($table)) {
            $this->select($table, $where, $limit, $order, $where_mode, 'COUNT(*)');
        }
        $res = $this->row();
        return $res->{'COUNT(*)'};
    }
    /**
     * Check if a table with a specific name exists
     *
     * @param $name
     * @return bool
     */
    function table_exists($name)
    {
        $res = mysqli_query($this->mysql, "SELECT COUNT(*) AS count FROM information_schema.tables WHERE table_schema = '" . $this->escape($this->database_name) . "' AND table_name = '" . $this->escape($name) . "'");
        return ($this->mysqli_result($res, 0) == 1);
    }
    /**
     * Helper function for process_where
     *
     * @param $array
     * @return string
     */
    private function join_array($array)
    {
        $nr = 0;
        $query = '';
        foreach ($array as $key => $value) {
            if (is_object($value) || is_array($value) || is_bool($value)) {
                $value = serialize($value);
            }
            $query .= " '" . $this->escape($value) . "'";
            $nr++;
            if ($nr != count($array)) {
                $query .= ',';
            }
        }
        return trim($query);
    }
    /* Insert/update functions */
    /**
     * Insert a row in a table
     *
     * @param $table
     * @param array $fields
     * @param bool|false $appendix
     * @param bool|false $ret
     * @return bool|Database
     * @throws Exception
     */
    function insert($table, $fields = array(), $appendix = false, $ret = false)
    {
        $this->result = null;
        $this->sql = null;
        $query = 'INSERT INTO';
        $query .= ' `' . $this->escape($table) . "`";
        if (is_array($fields)) {
            $query .= ' (';
            $num = 0;
            foreach ($fields as $key => $value) {
                $query .= ' `' . $key . '`';
                $num++;
                if ($num != count($fields)) {
                    $query .= ',';
                }
            }
            $query .= ' ) VALUES ( ' . $this->join_array($fields) . ' )';
        } else {
            $query .= ' ' . $fields;
        }
        if ($appendix) {
            $query .= ' ' . $appendix;
        }
        if ($ret) {
            return $query;
        }
        $this->sql = $query;
        $this->result = mysqli_query($this->mysql, $query);
        if (mysqli_error($this->mysql) != '') {
            $this->_error(mysqli_error($this->mysql));
            $this->result = null;
            return false;
        } else {
            return $this;
        }
    }
    /**
     * Execute an UPDATE statement
     *
     * @param $table
     * @param array $fields
     * @param array $where
     * @param bool $limit
     * @param bool $order
     * @return $this|bool
     * @throws DatabaseException
     */
    function update($table, $fields = array(), $where = array(), $limit = false, $order = false)
    {
        if (empty($where)) {
            throw new DatabaseException('Where clause is empty for update method');
        }
        $this->result = null;
        $this->sql = null;
        $query = 'UPDATE `' . $table . '` SET';
        if (is_array($fields)) {
            $nr = 0;
            foreach ($fields as $k => $v) {
                if (is_object($v) || is_array($v) || is_bool($v)) {
                    $v = serialize($v);
                }
                $query .= ' `' . $k . "`='" . $this->escape($v) . "'";
                $nr++;
                if ($nr != count($fields)) {
                    $query .= ',';
                }
            }
        } else {
            $query .= ' ' . $fields;
        }
        if (!empty($where)) {
            $query .= ' WHERE' . $this->process_where($where);
        }
        if ($order) {
            $query .= ' ORDER BY ' . $order;
        }
        if ($limit) {
            $query .= ' LIMIT ' . $limit;
        }
        $this->sql = $query;
        $this->result = mysqli_query($this->mysql, $query);
        if (mysqli_error($this->mysql) != '') {
            $this->_error(mysqli_error($this->mysql));
            $this->result = null;
            return false;
        } else {
            return $this;
        }
    }
    /**
     * Execute a DELETE statement
     *
     * @param $table
     * @param array $where
     * @param string $where_mode
     * @param bool $limit
     * @param bool $order
     * @return $this|bool
     * @throws DatabaseException
     * @throws Exception
     */
    function delete($table, $where = array(), $where_mode = "AND", $limit = false, $order = false)
    {
        if (empty($where)) {
            throw new DatabaseException('Where clause is empty for update method');
        }
        // Notice: different syntax to keep backwards compatibility
        $this->result = null;
        $this->sql = null;
        $query = 'DELETE FROM `' . $table . '`';
        if (!empty($where)) {
            $query .= ' WHERE' . $this->process_where($where, $where_mode);
        }
        if ($order) {
            $query .= ' ORDER BY ' . $order;
        }
        if ($limit) {
            $query .= ' LIMIT ' . $limit;
        }
        $this->sql = $query;
        $this->result = mysqli_query($this->mysql, $query);
        if (mysqli_error($this->mysql) != '') {
            $this->_error(mysqli_error($this->mysql));
            $this->result = null;
            return false;
        } else {
            return $this;
        }
    }
    /**
     * Get the primary key of the last inserted row
     *
     * @return int|string
     */
    public function id()
    {
        return mysqli_insert_id($this->mysql);
    }
    /**
     * Get the number of rows affected by your last query
     *
     * @return int
     */
    public function affected()
    {
        return mysqli_affected_rows($this->mysql);
    }
    /**
     * Escape a parameter
     *
     * @param $str
     * @return string
     */
    public function escape($str)
    {
        return mysqli_real_escape_string($this->mysql, $str);
    }
    /**
     * Get the last error message
     *
     * @return string
     */
    public function error()
    {
        return mysqli_error($this->mysql);
    }
    /**
     * Fix UTF-8 encoding problems
     *
     * @param $str
     * @return string
     */
    private function clean($str)
    {
        if (is_string($str)) {
            if (!mb_detect_encoding($str, 'UTF-8', TRUE)) {
                $str = utf8_encode($str);
            }
        }
        return $str;
    }
    /**
     * Check if a variable is serialized
     *
     * @param mixed $data
     * @param null $result
     * @return bool
     */
    public function is_serialized($data, &$result = null)
    {
        if (!is_string($data)) {
            return false;
        }
        $data = trim($data);
        if (empty($data)) {
            return false;
        }
        if ($data === 'b:0;') {
            $result = false;
            return true;
        }
        if ($data === 'b:1;') {
            $result = true;
            return true;
        }
        if ($data === 'N;') {
            $result = null;
            return true;
        }
        if (strlen($data) < 4) {
            return false;
        }
        if ($data[1] !== ':') {
            return false;
        }
        $lastc = substr($data, -1);
        if (';' !== $lastc && '}' !== $lastc) {
            return false;
        }
        $token = $data[0];
        switch ($token) {
            case 's' :
                if ('"' !== substr($data, -2, 1)) {
                    return false;
                }
                break;
            case 'a' :
            case 'O' :
                if (!preg_match("/^{$token}:[0-9]+:/s", $data)) {
                    return false;
                }
                break;
            case 'b' :
            case 'i' :
            case 'd' :
                if (!preg_match("/^{$token}:[0-9.E-]+;/", $data)) {
                    return false;
                }
        }
        try {
            if (($res = @unserialize($data)) !== false) {
                $result = $res;
                return true;
            }
            if (($res = @unserialize(utf8_encode($data))) !== false) {
                $result = $res;
                return true;
            }
        } catch (Exception $e) {
            return false;
        }
        return false;
    }
    /**
     * MySQL compatibility method mysqli_result
     * http://www.php.net/manual/en/class.mysqli-result.php#109782
     *
     * @param mysqli_result $res
     * @param int $row
     * @param int $field
     */
    private function mysqli_result($res, $row, $field = 0)
    {
        $res->data_seek($row);
        $datarow = $res->fetch_array();
        return $datarow[$field];
    }
}
Heb je die echt nodig?
In PHP heb je ook een standaard MySQLi of PDO-class die je kan gebruiken.

Persoonlijk vind ik een class maken een beetje het wiel opnieuw uitvinden. Je kan voor het gemak zelf ook een 'wrapper' maken zodat je zelf in je class kan beslissen of je MySQLi, PDO, Oracle of wat dan ook wilt gebruiken, zonder dat je heel je script moet aanpassen bij een wijziging.

Het is net hoever je wilt gaan, een hoeveel tijd je wilt investeren. De wereld van OOP is erg groot te noemen.

Reageren