PHP Classes and OOP

PHP Classes are used to store variables and functions of a particular topic in one class.

To create a class, we just need to use the keyword class and then give our class a name. Inside these curly braces {} we will store many functions for our User class.

<?php

    class User{
    }
?>

Variables inside classes are called properties. So let's add a few to our class.

<?php

    class User{
        public $age;
        public $fullName
    }
?>

If the name has more than one word, it has to be written in camelcase. For example: codingIsCool. All the words have to be written together, and the first word has to be with a lower case, and then all the other words have to start with a capital case.

The keyword public has to be put in front of our property because it is available from everywhere.

If we want to add objects to our class, we have to use the new keyword.

$bobby = new User();

Let's set the properties to our object.

$bobby -> age = '27';
$bobby -> fullName = 'Bobby Iliev';

If you want to check an object's property, you can just echo it out.

echo $bobby -> age;
echo $bobby -> fullName;

Remember that the property name does not start with the $ sign, only the object name begins with a $.

Now finally, let's add a function to our class. Functions inside of classes are also referred to as methods. Let's add our method.

<?php

    class User{
        public $age;
        public $fullName
        public $info{
            return 'Your full name is ' . $this->fullName;, . and your age is . $this->age;
        }
    }
?>

Now, let's echo out our function.

echo $bobby -> info();

For more about PHP classes, make sure to check out this tutorial!

https://devdojo.com/devdojo/php-classes-in-a-nutshell