Stefan's full name: Stefan Mischook
Nick's full name: Nick Waddles
Warning: Undefined variable $pinn_number in /var/www/html/php8/ch7/killerphp/pag-15/index.php on line 21

Warning: Undefined property: person::$ in /var/www/html/php8/ch7/killerphp/pag-15/index.php on line 21
Tell me private stuff:
Warning: Undefined variable $pinn_number in /var/www/html/php8/ch7/killerphp/pag-15/index.php on line 22

Warning: Undefined property: person::$ in /var/www/html/php8/ch7/killerphp/pag-15/index.php on line 22
Tell me private stuff:
index.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>OOP In PHP</title>
        <?php include("class_lib.php");?>
    </head>
    <body>
        <?php
        $stefan = new person("Stefan Mischook");
        $jimmy = new person("Nick Waddles");

        echo "Stefan's full name: " . $stefan->get_name();
        echo "</br>";
        echo "Nick's full name: " . $jimmy->get_name();

        /*
        Since $pinn_number was declared private, this line of code
        will generate an error. Try it out! 
        */
        echo "Tell me private stuff: " . $stefan->$pinn_number;
        echo "Tell me private stuff: " . $jimmy->$pinn_number;
        ?>
    </body>
</html>

class_lib.php_

<?php
 class person {
    var $name;
    public $height;
    protected $social_insurance;
    private $pinn_number;

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

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

    Omit the dollar sign when calling an object property. So instead of $jimmy->$pinn_number, you'd use $jimmy->pinn_number.

    There are some rather outdated things I see in the posted code (the use of var and snake case in variable and method declarations specifically); you might want to see if you can find a more modern tutorial.

    Write a Reply...