8 / 100 SEO Score

– Beginner to Intermediate Guide

In the previous chapter, we learned how to work with arrays and perform different operations on them. Now, we move one step forward and explore functions and classes, two powerful concepts that help you write clean, reusable, and well-structured PHP code.

Functions and classes are the foundation of professional PHP development. They allow you to organize logic, reduce repetition, and build scalable web applications.


What Are Functions in PHP?

A function is a reusable block of code that performs a specific task. Instead of writing the same logic again and again, you can define it once and call it whenever needed.

Functions can:

  • Accept input (parameters)
  • Process data
  • Return output

Defining a Simple Function

<?php
function helloWorld() {
    echo "Hello World";
}
?>

This function is defined but not executed yet. To run it, we must call it.

<?php
helloWorld();
?>

Functions with Parameters

Functions become more useful when they accept parameters.

<?php
function helloUser($name) {
    echo "Hello World, " . $name;
}

helloUser("John");
?>

Default Function Parameters

You can also define default values for parameters.

<?php
function displayMessage($message = "World") {
    echo "Hello " . $message;
}

displayMessage();
displayMessage("Greg");
?>

Functions That Return Values

Functions are not limited to printing text. They can also return values.

<?php
function addNumbers($a, $b) {
    return $a + $b;
}

echo addNumbers(5, 6);
?>

Returned values can also be stored in variables.

<?php
$sum = addNumbers(1, 2);
?>

Practical Example: Discount Calculator Function

<?php
$sweaterPrice = 50;
$percentOff = 0.25;

function couponCode($price, $discount) {
    return $price * $discount;
}

echo "The sweater originally costs $" . $sweaterPrice .
" and after discount you pay $" .
($sweaterPrice - couponCode($sweaterPrice, $percentOff));
?>

This example shows how functions help keep calculations clean and reusable.


Introduction to Classes in PHP

A class is a blueprint for creating objects. Classes are part of Object-Oriented Programming (OOP) and allow you to group data (variables) and behavior (functions) together.

Think of a class as a design, and an object as the real instance created from that design.

Creating a Simple Class

<?php
class Student {
}
?>

Class Properties (Member Variables)

<?php
class Student {
    public $name;
    public $age;
    public $major;
}
?>

The public keyword means these properties can be accessed directly.

Creating an Object

<?php
$michael = new Student();
$michael->name = "Michael John";
$michael->age = 27;
$michael->major = "Computer Science";
?>

Constructors in PHP Classes

A constructor is a special function that runs automatically when an object is created.

<?php
class Student {
    public $name;
    public $age;
    public $major;

    public function __construct($name, $age, $major) {
        $this->name = $name;
        $this->age = $age;
        $this->major = $major;
    }
}

$michael = new Student("Michael John", 27, "Computer Science");
?>

Private Properties and Getter Methods

<?php
class Student {
    private $name;
    private $age;
    private $major;

    public function __construct($name, $age, $major) {
        $this->name = $name;
        $this->age = $age;
        $this->major = $major;
    }

    public function getMajor() {
        return $this->major;
    }
}
?>

Private properties improve security and control access to data.


Inheritance in PHP

Inheritance allows one class to inherit properties and methods from another.

<?php
class Animal {
    public $name;
    public $sound;

    public function speak() {
        echo $this->name . " says " . $this->sound;
    }
}

class Dog extends Animal {
    public $name = "Dog";
    public $sound = "Woof! Woof!";
}

$dog = new Dog();
$dog->speak();
?>

Static Methods in PHP

Static methods can be called without creating an object.

<?php
class Animal {
    public static function about() {
        echo "This is the animal base class.";
    }
}

echo Animal::about();
?>

Conclusion

Functions and classes help you write clean, professional, and scalable PHP applications. Functions reduce repetition, while classes organize data and logic into structured components.

Mastering these concepts prepares you for advanced PHP frameworks like Laravel and real-world backend development.

225 thoughts on “Functions and Classes in PHP”

  1. XEvil 5.0 automatically solve most kind of captchas,
    Including such type of captchas: ReCaptcha-2, ReCaptcha v.3, Google captcha, Solve Media, BitcoinFaucet, Steam, +12000
    + hCaptcha, FC, ReCaptcha Enterprize now supported in new XEvil 6.0!
    + CloudFlare TurnsTile, GeeTest captcha now supported in new XEvil 7.0!
    + XEvil 7.0 was released! ReCaptcha v2 solving speed increased x2!
    + XEvil can solve captchas from OpenClaw AI bot!

    1.) Fast, easy, precisionly
    XEvil is the fastest captcha killer in the world. Its has no solving limits, no threads number limits

    2.) Several APIs support
    XEvil supports more than 6 different, worldwide known API: 2Captcha, anti-captchas (antigate), RuCaptcha, DeathByCaptcha, etc.
    just send your captcha via HTTP request, as you can send into any of that service – and XEvil will solve your captcha!
    So, XEvil is compatible with hundreds of applications for SEO/SMM/password recovery/parsing/posting/clicking/cryptocurrency/etc.

    3.) Useful support and manuals
    After purchase, you got access to a private tech.support forum, Wiki, Skype/Telegram online support
    Developers will train XEvil to your type of captcha for FREE and very fast – just send them examples

    4.) How to get free trial use of XEvil full version?
    – Try to search in Google “Home of XEvil”
    – you will find IPs with opened port 80 of XEvil users (click on any IP to ensure)
    – try to send your captcha via 2captcha API ino one of that IPs
    – if you got BAD KEY error, just tru another IP
    – enjoy! 🙂
    – (its not work for hCaptcha!)

    WARNING: Free XEvil DEMO does NOT support ReCaptcha, hCaptcha and most other types of captcha!

    Reply
  2. Ищете надежные лицензии для 1С-Битрикс? Мы предлагаем легальные решения для всех типов проектов: интернет-магазинов, корпоративных сайтов и порталов. Переходите по запросу cms Bitrix 1С. Быстрая активация, официальная поддержка и выгодные условия – обеспечьте своему веб-проекту стабильную работу и защиту с надежным ПО уже сегодня!

    Reply
  3. Старый паркет? шлифовка паркета без пыли профессиональное восстановление деревянного пола без пыли и лишних затрат. Удаляем царапины, потемнения и старое покрытие, возвращаем гладкость и естественный цвет. Используем современное оборудование, выполняем циклевку, шлифовку и лакировку паркета под ключ с гарантией качества и точным соблюдением сроков.

    Reply
  4. Абраменко Светлана Александровна Ищете ли вы решение для корпоративного видео, рекламного ролика, или хотите запечатлеть знаменательное событие, Светлана Александровна и ее команда готовы предложить индивидуальный подход и безупречное исполнение.

    Reply
  5. Синекс Синекс» стал еще ближе! Мы открылись в ЖК Крымская Роза. По адресу Проспект Александра Суворова 107, пом 2К Теперь жители микрорайона могут сдавать любые анализы без очередей и в шаговой доступности. Современное оборудование Быстрые и точные результаты Широкий спектр исследований: от общих анализов крови до сложных До сложных генетических панелей. ! Более 3500 анализов. Удобный график работы В новом пункте «Синекс» доступны: Клинические исследования крови и мочи Биохимия Гормональные профили Диагностика инфекций Генетические панели Мы рядом, когда это важно! Телефон горячей линии 8 800 333 01 09

    Reply
  6. XEvil 5.0 automatically solve most kind of captchas,
    Including such type of captchas: ReCaptcha-2, ReCaptcha-3, Google, SolveMedia, BitcoinFaucet, Steam, +12000
    + hCaptcha, FC, ReCaptcha Enterprize now supported in new XEvil 6.0!
    + CloudFlare TurnsTile, GeeTest captcha now supported in new XEvil 7.0!
    + XEvil 7.0 was released! ReCaptcha v2 solving speed increased x2!
    + XEvil can solve captchas from OpenClaw AI bot!

    1.) Fast, easy, precisionly
    XEvil is the fastest captcha killer in the world. Its has no solving limits, no threads number limits

    2.) Several APIs support
    XEvil supports more than 6 different, worldwide known API: 2Captcha, anti-captcha (antigate), RuCaptcha, death-by-captcha, etc.
    just send your captcha via HTTP request, as you can send into any of that service – and XEvil will solve your captcha!
    So, XEvil is compatible with hundreds of applications for SEO/SMM/password recovery/parsing/posting/clicking/cryptocurrency/etc.

    3.) Useful support and manuals
    After purchase, you got access to a private tech.support forum, Wiki, Skype/Telegram online support
    Developers will train XEvil to your type of captcha for FREE and very fast – just send them examples

    4.) How to get free trial use of XEvil full version?
    – Try to search in Google “Home of XEvil”
    – you will find IPs with opened port 80 of XEvil users (click on any IP to ensure)
    – try to send your captcha via 2captcha API ino one of that IPs
    – if you got BAD KEY error, just tru another IP
    – enjoy! 🙂
    – (its not work for hCaptcha!)

    WARNING: Free XEvil DEMO does NOT support ReCaptcha, hCaptcha and most other types of captcha!

    http://xrumersale.site/

    Reply
  7. Лицензия «Битрикс: Управление сайтом – Старт» — оптимальное решение для создания небольшого сайта, лендинга или корпоративной страницы. Переходите по запросу лицензия Битрикс Старт. Редакция включает базовые инструменты для управления контентом, готовые модули, защиту сайта и удобную административную панель. Подходит для быстрого запуска проекта на CMS 1C-Битрикс с возможностью дальнейшего масштабирования и перехода на более функциональные редакции.

    Reply
  8. Новые пользователи сайта часто получают акции и бонусы за регистрацию и первые депозиты.
    Посетите 7k casino для быстрого доступа к играм и бонусам.

    Отзывы игроков помогают улучшать сервис и устранять недочеты.
    Официальный сайт предлагает турниры и временные акции для повышения интереса к играм.
    В случае проблем с контролем игрового поведения поддержка подсказывает контакты служб помощи и процедуры самоисключения.
    Участие в турнирах предполагает борьбу за место в таблице лидеров и получение призов.

    Reply
  9. Современная медицина требует от клиник и косметологических салонов оборудования, способного решать широкий спектр задач без компромиссов в качестве. Российская компания ЛазМедТек создала многофункциональный лазерный комплекс LASEST, объединяющий в одном устройстве модули для хирургии, эстетической дерматологии, гинекологии и физиотерапии. Подробнее о возможностях оборудования и условиях приобретения можно узнать на сайте https://lasest.ru/ — там же представлены технические характеристики всех лазерных модулей, от Nd:YAG до CO2 Dynamic. Комплекс позволяет выполнять лазерную эпиляцию, удаление татуировок, лечение сосудистых патологий и даже остеоартроза, обеспечивая клинике быструю окупаемость и мобильность. Это универсальное решение для специалистов, которые ценят точность и эффективность.

    Reply
  10. 1C-Bitrix: Управление сайтом — редакция Стандарт — это мощная платформа для создания и управления корпоративными сайтами. Переходите по запросу Битрикс Стандартная лицензия цена. Подходит для компаний, которым нужен функциональный сайт с каталогом, формами, SEO-инструментами и удобной системой администрирования. Решение обеспечивает высокую безопасность, производительность и гибкость масштабирования бизнеса в интернете.

    Reply
  11. XEvil 5.0 automatically solve most kind of captchas,
    Including such type of captchas: ReCaptcha-2, ReCaptcha v.3, Google captcha, SolveMedia, BitcoinFaucet, Steam, +12k
    + hCaptcha, FC, ReCaptcha Enterprize now supported in new XEvil 6.0!
    + CloudFlare TurnsTile, GeeTest captcha now supported in new XEvil 7.0!
    + XEvil 7.0 was released! ReCaptcha v2 solving speed increased x2!
    + XEvil can solve captchas from OpenClaw AI bot!

    1.) Fast, easy, precisionly
    XEvil is the fastest captcha killer in the world. Its has no solving limits, no threads number limits

    2.) Several APIs support
    XEvil supports more than 6 different, worldwide known API: 2Captcha, anti-captcha (antigate), RuCaptcha, death-by-captcha, etc.
    just send your captcha via HTTP request, as you can send into any of that service – and XEvil will solve your captcha!
    So, XEvil is compatible with hundreds of applications for SEO/SMM/password recovery/parsing/posting/clicking/cryptocurrency/etc.

    3.) Useful support and manuals
    After purchase, you got access to a private tech.support forum, Wiki, Skype/Telegram online support
    Developers will train XEvil to your type of captcha for FREE and very fast – just send them examples

    4.) How to get free trial use of XEvil full version?
    – Try to search in Google “Home of XEvil”
    – you will find IPs with opened port 80 of XEvil users (click on any IP to ensure)
    – try to send your captcha via 2captcha API ino one of that IPs
    – if you got BAD KEY error, just tru another IP
    – enjoy! 🙂
    – (its not work for hCaptcha!)

    WARNING: Free XEvil DEMO does NOT support ReCaptcha, hCaptcha and most other types of captcha!

    http://xrumersale.site/

    Reply
  12. 7777jli is a blast from the past! Kinda retro vibe, which I dig! Games load fast, and I’ve had some okay luck so far. Def worth a look if you like a bit of old-school charm. Try it at 7777jli. Good times!

    Reply
  13. Installed the gugobetapk on my phone super easy. I like being able to play some games on the move. The app feels safe and I have easily made withdrawals. Check it out today at gugobetapk It could be your next spot for some fun!

    Reply
  14. Битрикс: Управление сайтом Малый Бизнес — функциональная редакция CMS для создания интернет-магазинов и коммерческих проектов. Переходите по запросу Bitrix Малый Бизнес скачать. Система включает каталог товаров, корзину, онлайн-оплаты, маркетинговые инструменты и интеграцию с 1С. Решение подходит для компаний, которым нужен надежный и масштабируемый сайт с возможностью расширения функционала через модули и интеграции.

    Reply
  15. Военная психотравма, острые кризисные состояния Наш подход основан на глубоком уважении к личности, конфиденциальности и стремлении к достижению устойчивых позитивных изменений, позволяя каждому клиенту раскрыть свой потенциал и жить полноценной, гармоничной жизнью.

    Reply
  16. XEvil 6.0 automatically solve most kind of captchas,
    Including such type of captchas: ReCaptcha v.2, ReCaptcha v.3, Google, SolveMedia, BitcoinFaucet, Steam, +12000
    + hCaptcha, FC, ReCaptcha Enterprize now supported in new XEvil 6.0!
    + CloudFlare TurnsTile, GeeTest captcha now supported in new XEvil 7.0!
    + XEvil 7.0 was released! ReCaptcha v2 solving speed increased x2!
    + XEvil can solve captchas from OpenClaw AI bot!

    1.) Fast, easy, precisionly
    XEvil is the fastest captcha killer in the world. Its has no solving limits, no threads number limits

    2.) Several APIs support
    XEvil supports more than 6 different, worldwide known API: 2Captcha, anti-captcha (antigate), RuCaptcha, death-by-captcha, etc.
    just send your captcha via HTTP request, as you can send into any of that service – and XEvil will solve your captcha!
    So, XEvil is compatible with hundreds of applications for SEO/SMM/password recovery/parsing/posting/clicking/cryptocurrency/etc.

    3.) Useful support and manuals
    After purchase, you got access to a private tech.support forum, Wiki, Skype/Telegram online support
    Developers will train XEvil to your type of captcha for FREE and very fast – just send them examples

    4.) How to get free trial use of XEvil full version?
    – Try to search in Google “Home of XEvil”
    – you will find IPs with opened port 80 of XEvil users (click on any IP to ensure)
    – try to send your captcha via 2captcha API ino one of that IPs
    – if you got BAD KEY error, just tru another IP
    – enjoy! 🙂
    – (its not work for hCaptcha!)

    WARNING: Free XEvil DEMO does NOT support ReCaptcha, hCaptcha and most other types of captcha!

    Reply
  17. Шкафы на балкон Независимо от выбранного типа, мы позаботимся о полной отделке балкона или лоджии, делая их не только красивыми, но и максимально функциональными.

    Reply
  18. игры вавада Играть на Vavada – значит выбрать лучшее из мира онлайн-гемблинга, где каждый игрок чувствует себя особенным, а азарт сочетается с комфортом и безопасностью.

    Reply
  19. gana777 Casino Gana777 – это место, где азарт встречается с инновациями, а каждый спин и каждая ставка приближают вас к заветному джекпоту.

    Reply
  20. Продвижение сообщества или страницы во ВКонтакте с помощью привлечения подписчиков. Услуга помогает быстро увеличить аудиторию, повысить активность и доверие к группе или профилю. Переходите по запросу сколько стоит привлечение 1 подписчика в вк. Возможна накрутка живых и заинтересованных пользователей, что улучшает видимость сообщества, помогает быстрее развивать бренд, проекты и продажи. Подходит для групп, пабликов и личных страниц.

    Reply

Leave a Comment