Friday 1 February 2019

How to create a class in PHP

The code is this simple:
 
class MyClass {
 
}
 
Not much to it.
 
Of course, inside that you'll then put your property and method declarations:
 
class MyClass {
    public $var = 'I like OOP';
 
    public function my_function() {
        return $this->var;
    }
}
 
So, now you know classes, properties and methods.
 
You instantiate an instance of this class, like so:
 
$myClass = new MyClass;
 
You can pass parameters to a class by having a class constructor, like this:
 
class MyClass {
    public $var = 'I like OOP';
 
    public function __construct($myvar) {
        $this->var = $myvar;
 
        return $this->var;
    }
}
 
$myClass = new MyClass('OOP is dope');
echo $myClass->var;
 
Point is, I find a lot of developers get intimidated by object-oriented programming. Probably, because most tutorials start out trying to teach you about barking dogs and people with brown eyes walking and all the weird analogies you find out there.
 
That stuff is important.
 
But, can be confusing.
 
Anyway, I make my stuff more approachable. The big thing to get about OOP is it's really about application-building. And, it doesn't just make for better applications... it makes building them easier. It really does.
 
In any case, if you haven't learned this, yet, give my OOP in PHP course a try.
 
There's only a few weird analogies, I promise. :D
Previous Post
Next Post

post written by:

0 Comments:

Hit me with a comment!