简体   繁体   中英

How to add elements to an array that is a property of an object in PHP?

I would like to be able to have an object which contains an array as a property. I would like to be able to add elements to that array. I get the errors: Warning: array_push() expects parameter 1 to be array, null given in /wwwg32Np9 on line 18 vw1997Array (I am running this in w3schools demo pages)

<!DOCTYPE html>
<html>
<body>

<?php
class Car {
    public $model; 
    public $year; 
    public $passengers;

    function __construct() {
        $this->model = "";
        $this->year = " ";
        $this->passengers=array(); //?not sure if this is right
    }
//wrote a function to see if I could add elements to the array this way

function addPassengers($passenger)
    {
        array_push($passengers, $passenger); 
        return $passengers; 
    }
}
// create an object
$herbie = new Car(); 
$herbie->model = "vw"; 
$herbie->year = "1997"; 
$herbie->addPassengers("Mike"); //? is this right? 

// show object properties
echo $herbie->model;
echo $herbie->year; 
echo $herbie->passengers;  //?is this right? 
?>

</body>
</html>

You need to do 2 changes:

1.Use $this->passengers inside function.

2.Use print_r() to print it

<?php

class Car {
    public $model; 
    public $year; 
    public $passengers;

    function __construct() {
        $this->model = "";
        $this->year = " ";
        $this->passengers=array();
    }

function addPassengers($passenger)
    {
        array_push($this->passengers, $passenger); 
        return $this->passengers; 
    }
}

$herbie = new Car(); 
$herbie->model = "vw"; 
$herbie->year = "1997"; 
$herbie->addPassengers("Mike");


echo $herbie->model;
echo $herbie->year; 
print_r($herbie->passengers);
?>

Output:- https://3v4l.org/aQn2h

Note:- You can write less amount of code and get the same output: https://3v4l.org/KTVAp

As other comments stated you need to use private variables instead of public

Sample example: - https://3v4l.org/8RF9j

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM