NothingiLLEGAL
http://forum.nothingillegal.com/forum/

How to properly use classes in PHP
http://forum.nothingillegal.com/forum/viewtopic.php?f=18&t=1268
Page 1 of 1

Author:  KimChoJapFan [ Sun Sep 10, 2017 19:31 pm ]
Post subject:  How to properly use classes in PHP

What are classes in PHP? : A class can be seen as a blueprint that stores functions and objects. That's not an all encompassing definition of what a class is in PHP; however, I believe you'll understand a little more about classes in PHP and Object-Oriented Programming (OOP) by the end of this tutorial.

Constants : A constant is a value that can not be changed.

Code:

class Example 
{
    const ENCTYPE = 'PASSWORD_ARGON2I';
    const METHOD = 'AES-256-CBC';
}
 


Visibility : In your PHP class you can make variables/functions with the following visibilities:
  • Public
  • Protected
  • Private

Public variables/functions are capable of being called from anywhere. It's best not to store sensitive information in a public variable/function.

Protected variables/functions are capable of being called from the class you made and any classes that extends the one you made. These are not publicly available and you're unlikely to be making use of protected variables/functions when you're learning about classes.

Private variables/functions are only capable of being called from the class you made. These are perfect for storing personal information since there's no chance of these variables/functions returning their contents to parts of the site that you didn't intend for them to wind up.

For this tutorial, we'll be making use of public variables since we won't be handling sensitive information.

Static Functions : Static functions can be called without initializing the class.

Code:

class Example 
{
    public static function helloWorld() {
        return 'Hello World!';
    }
}

echo Example::helloWorld();


The visibility rules still apply to static functions.

Interfaces : You probably won't encounter an interface unless you're building a container or a specific function set.
Here's an example of an interface because it's not as easy to define as I wish it were:
Code:

interface iLibrary 
{
    public function book($name, $dewey, $author, $date, $available);
}

class Library implements iLibrary {
    public function book($name, $dewey, $author, $date, $available) {
        return [
            'Name' => $name,
            'Dewey' => $dewey,
            'Author' => $author,
            'Date' => $date,
            'Available' => $available
        
];
    }
}

$library = new Library();
var_dump($library->book('Test', '100', 'John Doe', '1995', '1'));
 


In this case the programmer can not change the way the function appears and the number and name of the variables in the function.
This is useful if you're wanting to set up a specific manner of calling this function.

Extensions : Extensions are used to inherit the functions and variables of another class. You can only extend one class from another, there's no way to extend multiple classes from a single class.

You can also extend interfaces as well.

Code:

class Original 
{
    public function hello() {
        return 'Hello';
    }
}

class Extended extends Original {
    public function world() {
        return 'World';
    }
}

$ext = new Extended();
echo $ext->hello() . ' ' . $ext->world() . '!';


Anonymous Classes : Anonymous classes were added in PHP 7.0 (according to official documentation) and serve as a quick and dirty method of setting classes within variables.

Code:

interface Message 
{
    public function getMsg();
}

$msg = (new class() implements Message {
    public function getMsg() { return 'Message'; }
});

echo $msg->getMsg();
 


This might not come up very often unless you're extending classes.

Magic Methods : There are several magic methods that can be used in classes:
  • __construct
  • __destruct
  • __call
  • __callStatic
  • __get
  • __set
  • __isset
  • __unset
  • __sleep
  • __wakeup
  • __toString
  • __invoke
  • __set_state
  • __clone
  • __debugInfo

__construct: We've seen this method in the past, it's purpose is to inject parameters and dependencies into your classes. What that means is we can set variables upon calling the class that can be carried throughout the class and its extensions.

__destruct: The purpose of the destruct method is to clear up any injected parameters and dependencies set by our construct method. This is only really useful if you're wanting to clear sensitive information from an extended class that you don't want to be callable from the original class.

__call: The purpose of the call method is to allow you to be able to call a method that is not publicly accessible on the object. This is only really useful if you're wanting to return a special error message for when the programmer puts in an invalid function from the class.

__callStatic: This is the same as the call method but works similar to a static function instead.

__get: The purpose of the get method is to read data from inaccessible properties. This is useful if you want to receive data from a dynamically created function.

__set: The purpose of the set method is to write data to inaccessible properties. This is useful if you want to send data to a dynamically created function.

__isset: The purpose of the isset method is to determine if an inaccessible property contains data.

__unset: The purpose of the unset method is to clear out an inaccessible property.

__sleep: The purpose of the sleep method is to send pending data or other similar types of cleanup tasks. This is useful for large amounts of data.

__wakeup: The purpose of the wakeup method is to reestablish any database connections and perform re-initialization tasks.

__toString: The purpose of the toString method is to convert input data into a string format for printing out. This is only useful if you're wanting to convert valid data types such as boolean and integers into a string for storing/printing/manipulating.

__invoke: The purpose of the invoke method is to determine if a script is trying to be called as a function. This is only useful for when you want to return specialized errors to the programmer for when they attempt to call a class/interface as if it were a function.

__set_state: The purpose of the set_state method is to allow the var_export function to be eval'ed in PHP. This is only useful for when you're parsing templates with array values.

__clone: The purpose of the clone method is to copy the value of a function for separate manipulation. This can come in real handy if you want to manipulate a function's output without having to call the same function multiple times.

__debugInfo: The purpose of the debugInfo method is to return the full information of a function when called by var_dump. This is only useful if you want to have the var_dump function return more information about the called function.

Now not all of this information is correct, there's a whole lot of other functionality that I am leaving out from these magic methods because I might not be able to see the purpose of each magic method pertaining to said functionality. To be honest, you'll probably wind up using the following magic methods in your projects:

  • __construct
  • __get
  • __set
  • __sleep
  • __wakeup
  • __clone

Otherwise you're dealing with a programming endeavor a bit beyond my grasp at this moment.

Serialization : There are two important functions in PHP called serialize and unserialize.

  • Serialize is important for storing functions in binary formatting to be loaded from another page. This can be useful for when you want to store user inputs in a binary file format for later use (can be useful if you're wanting to increase script performance by trading off disk space).
  • Unserialize is important for loading functions from binary formatting to be ran from another page.

Code:

class Example 
{
    public $helloWorld = 'Hello World!';

    public function greetings() {
        echo $this->helloWorld;
    }
}

$ex = new Example();
$exs = serialize($ex); // This is now serialized and can be written to a binary file.

$exa = unserialize($exs); // This is now unserialized and can be ran like normal.
$exa->greetings(); // This should print out "Hello World!"
 


Making our first class : Let's get a few things straight about how I handle database connections in PHP:
  • I never connect to a database with MySQL or MySQLi, nowadays I always stick with PDO.
  • I never make any query without prepared statements to prevent SQL injections.
  • I never store any user input without htmlspecialchars to prevent Persistent XSS vulnerabilities.

Okay with that in mind we'll start by making our first class:
Code:
// It's not mandatory that you use capitalization with class names, but it's standard practice to use capitalization for class names as so.
class Items {}


So we now have the first bit underway; we've given our class a name and now it's time to set up our construct function.
Code:

class Items 
{
    // We set up some public variables that will be used throughout the rest of this class.
    var $name, $value, $amount;

    // This is our construct class and yes it is mandatory to put the two underscores at the front of the function name.
    function __construct($name, $value, $amount) {
        
        
// What we're doing here is setting the public variables to whatever values we call this class with.
        $this->name = $name;
        $this->value = $value;
        $this->amount = $amount;
    }
}


Now we can add another function to this class to return our inputs:
Code:

class Items 
{
    var $name, $value, $amount;

    function __construct($name, $value, $amount) {
        $this->name = $name;
        $this->value = $value;
        $this->amount = $amount;
    }

    // Just set up a simple function that should return all inputs as an array.
    function toArray() {
    
        
// Return all public variables in a simple array.
        return [
            'Name' => $this->name, 
            
'Value' => $this->value, 
            
'Amount' => $this->amount
        
];
    }
}


To call upon our new function, we can do this:
Code:

class Items 
{
    var $name, $value, $amount;

    function __construct($name, $value, $amount) {
        $this->name = $name;
        $this->value = $value;
        $this->amount = $amount;
    }

    function toArray() {
        return [
            'Name' => $this->name, 
            
'Value' => $this->value, 
            
'Amount' => $this->amount
        
];
    }
}

// Create our new item.
$items = new Items('longsword', 10, 1);

// Print out our new item in a stylized fashion.
echo '<pre>';
print_r($items->toArray());
echo '</pre>';


That should output the data you put into the class.

Here is the screenshot of the code:

And here is the screenshot of the output that you should see:

TBD : 
This post will be modified under the following reasons:
  • Someone catches a mistake in this post and asks me to fix it.
  • I decide to add more examples or more information to this post.

So there's not a whole lot of other things I can think of adding to this tutorial.
Expect updates in the form of mistake fixes.

Page 1 of 1 All times are UTC + 1 hour
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
http://www.phpbb.com/