如何使用php类

时间:2017-08-03 18:52:46

标签: php arrays

我想将一些数组推入数组并将其保存在会话中。 我试图在php类中这样做。我是新手,所以我犯了一些错误,无法帮助我。

我的index.php

<?php 

session_start();
include("./cart.php");

//bezeichnung, preis, attribut
$myOrder = new Cart('17', 0.50, 'Book1');
$myOrder1 = new Cart('18', 1.50, 'Book2');
$_SESSION['products'] = array();
array_push($_SESSION['products'], $myOrder, $myOrder1);
echo '<pre>';
print_r($_SESSION['products']);
echo '</pre>';

我的cart.php

<?php

class Cart {
    private $name;
    private $price;
    private $attr;

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

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

    public function getPrice(){
        return $this->price;
    }

    public function getAttr(){
        return $this->attr;
    }
}

我得到这样的东西: 部分:Cart:private真的不好。这应该是juest名称,价格和attr。我想我将整个对象推入阵列。我怎么能避免这个?

Array
(
    [0] => Cart Object
        (
            [name:Cart:private] => 17
            [price:Cart:private] => 0.5
            [attr:Cart:private] => Book1
        )

    [1] => Cart Object
        (
            [name:Cart:private] => 18
            [price:Cart:private] => 1.5
            [attr:Cart:private] => Book2
        )
)

1 个答案:

答案 0 :(得分:0)

您可以在Cart类中执行一个公共方法,它将所有需要的属性作为数组返回。     

class Cart {
    private $name;
    private $price;
    private $attr;

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

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

    public function getPrice(){
        return $this->price;
    }

    public function getAttr(){
        return $this->attr;
    }

    public function toArray(){
        return array(
            'name' => $this->getName(),
            'price' => $this->getPrice(),
            'attr' => $this->getAttr(),
         );
    }

}

现在在index.php中你可以这样做:

 array_push($_SESSION['products'], $myOrder->toArray(), $myOrder1->toArray());