Overloading properties and methods in PHP - what is the reason?

Is it possible to use overload only for the reasons associated with using only nice features? :)

For instance:

echo $store->product->getPrice($currency);

  • product will call __get, then __getObject ('product'), which makes the magik material and returns the current product, which is considered as an object (it is created if this is the first call)

echo $store->product('dog')->getPrice($currency);

  • productwill call __call here , then __callObject ('product', ...) ...


An alternative without overload would be:
if(!$store->product)
  $store->product = new Product();

 echo $store->product->getPrice($currency);

and

$product = new Product('dog');
echo $product->getPrice($currency);

I really like overloading because I can get a good API for my classes. But the disadvantage is that overloaded material is 15 times slower than calling properties / methods directly.

Is it possible to use such an overload?

1000 . . , 0,1 , , 0,5-1 ,

+5
3

, ?:)

. , .:) :

$ordinary = new stdClass();
$ordinary->Caption = 'Hello';

class Awesome
{
   private $ordinary;
   public function __construct($ordinary) {
       $this->ordinary = (array) $ordinary;
   }
   public function __get($name) {
       $value = '';
       return $this->ordinary[$name];
   }
}

class Lovely extends Awesome
{
    public function __get($name)
    {
        return '<3 ' . parent::__get($name) . ' <3';
    }
}

, , -.

, , API . stdClass.

, -. , . API, :

$awesome = new Awesome($ordinary);

echo $awesome->Caption, "\n"; # This caption is just awesome by itself!
# Hello

API:

$lovely = new Lovely($ordinary);

echo $lovely->Caption, "\n"; # This caption is lovely, hughs and kisses everyone!
# <3 Hello <3

, Lovely, Awesome, Awesome :

$awesome = $ordinary;

, API . Lovely, ( ), , : Lovely , Awesome, ( ) __get :

    public function __get($name)
    {
        return '<3 ' . parent::__get($name) . ' <3';
    }

, Awesome - API, , , .

, ​​ , API . API , .

, / . API, , , [] ->. , ;)

, :

echo $store->getObject('product')->getPrice($currency);
+3

, " API", , . , " ": , , .

, . .

sidenote: , .

+3

Payouts are ensured by observing the principles of object-oriented design. The first example allows you to freely bind by creating a product object from a factory. For more on OO design principles, see SOLID and GRASP

+1
source

All Articles