开发者

Class Constructor PHP Help

anyone has an idea how to create a class in PHP then when called loads an array for example

$cart = new Cart(); //where Cart is the Class Name
print_R($cart); //print the constructor

At this Point I want something like this array

$cart = ([id] => ,[currency]=> ,[country]=> )

How anyone guide me how can I set up a constructor for this call,even if the properties are empty , I just want the key values for the array so that I can set its values like below

$cart->id = 1;
$cart->currency = EUR;
$cart->country= DE;

in this way it would be much easier to call in a new CART in th开发者_JS百科is example... and then manipulate the class properties in order to save to database etc


class Cart
{
    private $id, $currency, $country;

    public function __construct($id = 1, $currency = 'EUR', $country = 'DE')
    {
        $this->id = $id;
        $this->currency = $currency;
        $this->country = $country;
    }
}

If you pass no arguments to your constructor, it'll inherit the defaults in the function argument spec.


You shouldn't return an array in the constructor. You should always return the reference to the cart. Just add a method to get at your data.

class Cart {
    public $id = 1;
    public $currency = 'EUR';
    public $country  = 'DE'

   public function getData() {
      return array(
          'id' => $this->id,
          'currency' => $this->currency,
          'country'  => $this->country
      );
   }
}

$cart = new Cart();
print_r( $cart->getData() ); //will print the array

//you can also get at the property
$cart->id = 1;  
$cart->currency = 'EUR';
$cart->country= 'DE';


You could pass the values as parameters to the constructor of Cart

Like this:

 function __construct( Class $var ) {
        $this->var = $var;
 }

Or did I misunderstood your question?


I think you want to use the magic method __toString()

Example from the manual:

<?php
// Declare a simple class
class TestClass
{
    public $foo;

    public function __construct($foo)
    {
        $this->foo = $foo;
    }

    public function __toString()
    {
        return $this->foo;
    }
}

$class = new TestClass('Hello');
echo $class;
?>

Will output: Hello.

Change the method to return your array.


Print_r can do that. Just specify $id, $currency and $country as property and print will show you something like:

Cart Object ( [id:Cart:private] => 1 
              [currency:Cart:private] => EUR 
              [country:Cart:private] => DE 
            )

So i don't get your question


The constructor returns a reference to the object instance just created. It cannot return anything different.

You could implement a method inside your Cart object "toArray()" that returns an associative array "attribute" => "value", to fit your needs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜