DEV Community

Cover image for PHP __construct (🧙‍♂️Lesson 1: PHP Magic Methods)
Clean Code Studio
Clean Code Studio

Posted on • Edited on

5 2

PHP __construct (🧙‍♂️Lesson 1: PHP Magic Methods)

Twitter Follow


Today, we'll quickly cover the most popular PHP magic method - __construct.


__construct magic method


PHP allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.


Using the PHP __construct magic method


<?php

class User
{
    public $name;

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

$timmy = new User('Timmy');


echo $timmy->name;

// "Timmy"
Enter fullscreen mode Exit fullscreen mode

__construct PHP Magic Method



Did you know I have a newsletter? 📬

If you want to get notified when I publish new blog posts or make major project announcements, head over to

https://cleancodestudio.paperform.co/

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (1)

Collapse
 
cleancodestudio profile image
Clean Code Studio

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay