0

i see some of the free class library do something very interesting like

wideimage, phpexcel do,it call like the following

$class = new WideImage;

//WideImage

$class->load()->resize()->addnoise()->saveToFile();

i would like to learn it, but i got no idea, i think it use the function __call(){} but i tried and it not work, can someone teach me how? and i try to search around stackoverflow and also google, but i don't know what the keyword should i search LOL.

<?php

namespace system\classes {

    if(!defined('IN_APP')){

        exit('ACCESS DENIED.');

    }

    class images
    {

        protected $_root;
        protected $_attachment;
        protected $_image_path;
        protected $image;
        public $image_container;

        public function __construct(){

            global $_G;

            $this->_root = getglobal('attachment/path/root');
            $this->_attachment = getglobal('attachment/path/sub');
            $this->_image_path = $this->_root . DS . $this->_attachment . DS . getglobal('attachment/path/images') . DS;

            if(!$this->image || $this->image == '' || null($this->image)){

                $this->image = new \system\classes\wideimage\WideImage();

            }

        }

        public function load($var){
            $matrix = array(array(2,0,0),array(0, -1, 0), array(0, 0, -1));
            // $this->image = $this->image->loadFromUpload($var)->crop(50,50)->resize(100,100)->rotate(200,200)->addNoise(300, 'mono')->applyConvolution($matrix, 1, 220);
            $this->image = $this->image->loadFromUpload($var);

            // exit(var_dump($this->_image_path));

        }

        public function resize($width, $height){

            $this->image = $this->image->resize($width, $height);

        }

        public function save(){
            // exit(var_dump($this->image_container));
            $this->image = $this->image->saveToFile('name.gif');

        }

        public function __call($name,$arg){

            exit(var_dump($name));

        }

    }

}

?>

and this is my test.php

if(isset($_FILES['img'])){

        $images = new system\classes\images();

        $images->load('img')->save();

        // $images->save();

    }

i tried the $images->load('img')->save();

and php throw me an error

Fatal error: Call to a member function save() on a non-object in

user259752
  • 1,065
  • 2
  • 9
  • 24

1 Answers1

1

The -> operator calls a method on an object. Therefore you have to return an object from your function, so you have something to call your methods on. Easiest way would be to just return $this, so you have the same object instance again that you used for the initial method call.

The keyword this falls under is method chaining.

Community
  • 1
  • 1
knittl
  • 246,190
  • 53
  • 318
  • 364