Create RAR file with password protection

I need to create a rar file with password protection. The following is my code.

use Zend\Filter\Compress\Rar;
class TestController {

    function testAction() {
        $rar        = new Rar();
        $parent_dir = sys_get_temp_dir()."/test".time();
        if(!is_dir($parent_dir)){
          mkdir($parent_dir, true);
          chmod($parent_dir, 0777);
        }

        foreach($arr as $id) { 

          $dir      = $parent_dir."/test_$id/";
          $filename = "test_$id.xml";
          if(!is_dir($dir)){
            mkdir($dir, true);
            chmod($dir, 0777);
          }
          $content  = 'some content goes here';        
          $f2       = fopen($dir.$filename, "w");
          fwrite($f2, $content);
          fclose($f2);
        }

        $rar_dir    = sys_get_temp_dir()."/";
        $rar_name   = "test.rar";
        $rar->setArchive($rar_dir.$rar_name);
        $rar->setCallback($this->rarCallback($rar_dir,$rar_name));
        $rar->setPassword('123');
        $rar->setTarget($parent_dir);
        $rar->compress($parent_dir);

        exit;
    }

    public function rarCallback($rar_dir, $rar_name)
    {

      header("Cache-Control: public");
      header("Content-Description: File Transfer");
      header("Content-Disposition: attachment; filename=$rar_name");
      header("Content-Type: application/download");
      header("Content-Transfer-Encoding: binary");
      readfile($rar_dir.$rar_name); 

    }
    }

From this i got a rar file but that is not password protected. I don’t understand what i am missing.

I think you missed the important notice in the documentation:

Rar Compression not supported

Due to restrictions with the Rar compression format, there is no compression available for free. When you want to compress files into a new Rar archive, you must provide a callback to the adapter that can invoke a Rar compression program.

This means, you can not create RAR files with plain PHP. (ZF is also plain PHP)
You need an external (command line) tool / program the create a RAR file with compression.

See also: zip - add files to rar archive using php - Stack Overflow