-1

I tried to print the array $array1 but it shows the error msg as

Notice: Undefined variable: array1 in D:\xampp\htdocs\trainig\Day4\accessmod.php on line 16 Warning: Invalid argument supplied for foreach() in D:\xampp\htdocs\trainig\Day4\accessmod.php on line 16

<?php 
    class AccessMode
    {
    public $integer_member = 1;
    protected $float_number = 2.5;
    private $string = "Tony";
    public $array1 = [5, 7, 9];
    function print_properties(){
        echo "public integer: ".$this->integer_member;
        echo "<br>";
        echo "protected float: ".$this->float_number;
        echo "<br>";
        echo "private string: ".$this->string;
        echo "<br>";
        echo "public array: ";
        foreach ($array1 as $av){
            echo $av." ";  
        }

       }

    }
     $a = new AccessMode();
    echo "<br>";
    echo " From AccessMode class <br>";
    $a->print_properties();
    ?>
Machavity
  • 30,841
  • 27
  • 92
  • 100

1 Answers1

1

You want to access a class member and not an variable, so you need to use $this. Code this should be:

foreach ($this->array1 as $av) {

Then the output is:

From AccessMode class
public integer: 1
protected float: 2.5
private string: Tony
public array: 5 7 9 

Code is then:

<?php
class AccessMode
{
    public $integer_member = 1;
    protected $float_number = 2.5;
    private $string = "Tony";
    public $array1 = [5, 7, 9];

    function print_properties()
    {
        echo "public integer: " . $this->integer_member;
        echo "<br>";
        echo "protected float: " . $this->float_number;
        echo "<br>";
        echo "private string: " . $this->string;
        echo "<br>";
        echo "public array: ";
        foreach ($this->array1 as $av)
        {
            echo $av . " ";
        }

    }

}

$a = new AccessMode();
echo "<br>";
echo " From AccessMode class <br>";
$a->print_properties();
?>
Roman Holzner
  • 5,738
  • 2
  • 21
  • 32