OOP part 19 Chaining Methods

Home Forums Bugs OOP part 19 Chaining Methods

Tagged: ,

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #1389
    jurgenmuca
    Participant

    error:Fatal error: Uncaught Error: Call to a member function save_file() on null in C:\xampp\htdocs\OOPtutorial\index.php:73 Stack trace: #0 {main} thrown in C:\xampp\htdocs\OOPtutorial\index.php on line 73

    Problem:

    public function sanitize($data){
    foreach($data as $key =>$value){
    $data[$key] = addslashes($value);
    //adds lashes to the data and puts it to the same space to sanitize this data
    }
    }

    When sanitize($data) is called in a method chain, it returns null, must return a class

    Fix:

    //add a line to return an object, in this case $this (as the object Signup itself)

    public function sanitize($data){
    foreach($data as $key =>$value){
    $data[$key] = addslashes($value);
    //adds lashes to the data and puts it to the same space to sanitize this data
    }
    return $this;
    }

     

    error: Warning: file_get_contents(mydata.json): Failed to open stream: No such file or directory in C:\xampp\htdocs\OOPtutorial\index.php on line 66

    code:

    public function save_file($filename){
    $old_data = file_get_contents($filename);
    $old_array = json_decode($old_data);

    $old_array[] = $this->data;
    $string = json_encode($old_array);
    file_put_contents($filename, $string);
    }

    Trying to open a file to read it’s data but the file does not exist

    Fix:

    Create the file in another function and add it to the chain

    public function createFile($filename){
    if(!file_exists($filename)){
    file_put_contents($filename, ”);
    }
    $this->filename = $filename;
    return $this;

    }

     

    error:Fatal error: Uncaught Error: Call to a member function read() on array in C:\xampp\htdocs\OOPtutorial\index.php:91 Stack trace: #0 {main} thrown in C:\xampp\htdocs\OOPtutorial\index.php on line 91

    Code:$result = $myClass->read(‘mydata.json’)->read();//typo

    Fix:

    $result = $myClass->create(‘my-data.json’)->read();

    //Make sure to check if the file is created with create() function then read from the file

    //Also make sure the filename is correct

     

     

     

     

Viewing 1 post (of 1 total)
  • You must be logged in to reply to this topic.