PHP OOP – Missing argument 1

oopPHP

I'm trying to make the switch to OOP. I found a pdf on the internet written by killerphp that seems useful. Followed his examples up 'till now because I got an error. The output is this:

Warning: Missing argument 1 for person::__construct(), called in
C:\xampp\htdocs\oop\index.php on line 15 and defined in
C:\xampp\htdocs\oop\class_lib.php on line 8

and

Notice: Undefined variable: persons_name in
C:\xampp\htdocs\oop\class_lib.php on line 10

Stefan's full name: Stefan Mischook

Nick's full name: Nick Waddles

This is index.php (the page that I run):

<?php
    require_once('class_lib.php');
?>
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>OOP in PHP</title>
</head>

    <body>
        <?php
            // Create object without constructor by calling a method
            $stefan = new person();
            $stefan->set_name("Stefan Mischook");
            echo "Stefan's full name: " . $stefan->get_name();

            echo "<br>";

            // Create object with constructor
            $jimmy = new person("Nick Waddles");
            echo "Nick's full name: " . $jimmy->get_name();

        ?>
    </body>
</html>

And here is the class:

<?php
    // A variable inside a class is called a "property"
    // Functions inside a class are called "methods"
    class person
    {
        var $name;

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

        function set_name($new_name)
        {
            $this->name = $new_name;
        }

        function get_name()
        {
            return $this->name;
        }
    }

    // $this can be considered a special OO PHP keyword

    // A class is NOT an object. The object gets created when you create an instance of the class.

    // To create an object out of a class you need to use the "new" keyword.

    // When accesign methods and properties of a class you use the -> operator.

    // A constructor is a built-in method that allows you to give your properties values when you create an object
?>

Nevermind the comments, I use them for learning. Thank you very much and please let me know if I need to edit my question before downrating. Cheers!

Best Answer

The problem is here:

// Create object without constructor by calling a method
$stefan = new person();                        // <-----
$stefan->set_name("Stefan Mischook");

You're not passing a required parameter to the constructor.

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

This (constructor) requires a $persons_name argument to construct a new instance of the person class.

Also (related), your comment // Create object without constructor by calling a method is not at all what the code is doing. You are calling the constructor, and that is the problem. Perhaps this was partially copied from some example, and you missed something?