0

I have tried to search the web for this but cannot find a solution for my problem.

I am implementing a shoppingcart that will send some variables to PayEx payment, but I am struggling with some Class and Public variables.

The code:

class PayEx
{
    public $price = '00';
    //$respons is xml
    private $respons;
    private $orderRef;

    function initialization()
    {       
        $this->clientIPAddress = $_SERVER['REMOTE_ADDR'];       
        $this->clientIdentifier = "USERAGENT=".$_SERVER['HTTP_USER_AGENT'];
        $params = array
        (
            'price' => $this->price
        );

        return $params;
    }
....

Before this code I have a SQL query that sets the value of $mainPrice, so what I want to do is something like this:

class PayEx
{
    public $price = $mainPrice;
}

But this is not working, what am I doing wrong?

Samsquanch
  • 8,866
  • 12
  • 50
  • 89
kimremme
  • 5
  • 2

4 Answers4

4

TL;TR

Before this code I have a SQL query that sets the value of $mainPrice

Ok, and you want to assign its value to the $price property. In that case: write a constructor that takes the $mainPrice as an argument, and assigns it to the $price property.
The details are all explained below


It's really quite simple: $mainPrice is (probably) a global variable (which is evil, but that's not the point here). the PayEx class has its own scope. its properties are to be initialized using constant values or in the constructor (using arguments you pass to it).

A class is a single, portable unit of code. It should therefor not depend on any variable outside of itself, just to do its business. Who's to say that this $mainPrice variable will be around every single time your class will be used/initialized? And more importantly: when will the private $price = $mainPrice; statement be evaluated? When the file containing the class definition is require'd? When the autoloader kicks in? When the first instance is created, or whenever an instance is created? Think about it... you know it doesn't really make sense in an OO context

What would be the appropriate thing to do is something like:

class PayEx
{
    private $price = null;
    /**
     * Constructors - They are there to initialize properties
     * @param $mainPrice = null - null makes it optional
     */
    public function __construct($mainPrice = null)
    {
        $this->price = $mainPrice
    }
}
$x = new PayEx(123);//price propery is 123
$y = new PayEx();//price property is null

The safest way to set properties, though, is, and will always be: to create custom getter/setter methods. These methods can, for example, preform additional checks on the values you are trying to assign to a property. If invalid data is provided, they can also throw exceptions, containing specific information on what went wrong, making your code easier to use, maintain, and debug:

class PayEx
{
    private $price = null;
    public function __construct($mainPrice = null)
    {
        if ($mainPrice !== null)
            $this->setPrice($mainPrice);
    }
    /**
     * Custom setter
     * @param float $price
     * @return $this
     * @throws \InvalidArgumentException
     */
    public function setPrice($price)
    {
        if (!is_numeric($price))
            throw new \InvalidArgumentException(
                sprintf(
                    '%s expected argument of type float, instead saw non-numeric %s',
                    __METHOD__,
                    gettype($price)
                )
            );
        $this->price = (float) $price;
        return $this;
    }
    /**
     * custom getter
     * @param null|string $format
     * @return float|string
     */
    public function getPrice($format = null)
    {
        if ($format === null)
            return $this->price;
        return sprintf($format, $this->price);
    }
}
$x = new PayEx(12.456);
echo $x->getPrice('%.2f');//echoes 12.45
var_dump($x->getPrice());//float 12.456

I hope this gives you some idea as to why getters and setters are used so often in bigger projects.

Community
  • 1
  • 1
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
1

You cannot use a var directly on class variables.

After your SQL and when you call your class you can define price.

// Your sql...

$payex = new PayEx();
$payex->price = $mainPrice;
fdehanne
  • 1,658
  • 1
  • 16
  • 32
  • While this is all true, it's better to use a function to set values inside a class, rather than directly setting them outside the class. – Machavity Jul 30 '14 at 14:46
  • @Machavity : Sure, this is just the quicker and easy way for him to set it. – fdehanne Jul 30 '14 at 14:50
  • 1
    can't recommend this, the class can't even work without the ``$mainPrice`` is set, this method allow to use the class without the requirements are set - better to use the ``constructor`` functions – ins0 Jul 30 '14 at 14:53
  • 1
    @djidi: It may be shorter, sure, but it makes your code less reliable: setters can validate data, assigning any old variable could cause unexpected behaviour (or bugs) to show up further down the line. This kind of code, then, is harder to debug – Elias Van Ootegem Jul 30 '14 at 15:00
0

if you want to set variables before the class can even start work use __construct functions in classes which are called when a new instance of the object is created.

class PayEx
{
    public $price = 0;

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

you can pass the price variable now wen creating objects from PayEx

$payExObject = new PayEx($mainPrice);

alternative you can use Getter and Setter Functions

class PayEx
{
    public $price = 0;

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

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

and pass variables like this

$payExObject = new PayEx();
$payExObject->setPrice($mainPrice);
ins0
  • 3,918
  • 1
  • 20
  • 28
0

Along with what @djidi suggested, you can also use a constructor:

class PayEx
{
    public function __construct($price = '00') {
        $this->price = $price;
    }
....

Which you would call like:

....
$payex = new PayEx($mainPrice);
....
Samsquanch
  • 8,866
  • 12
  • 50
  • 89