Is it possible to transfer the function of access to the included file?

I have a view class with a function to create a view

class view {
   //...
     public function build() {
         $view = $this;            
         $data = $this->resources->data;

         function s($value) {
            return \classes\tools\html\html::specialChars($value);
         }

         require $this->viewFile;
     }
    //...
   }

And viewing some view files

<?php var_dump($view);
// works fine, variables passed ok ?>

<?= s($data->someUnsafeString) ?> 
<?php //Fatal error: Call to undefined function s() ?>

I could define a function sin each view file, but I really don't want to do this.

I could pass the function as a variable $s=function(){..}, but I would prefer not too

I could call the static function in the view directly, but even longer than I would like:

<?= html::s($data->someUnsafeString) ?>

Is it possible? or any other suggestions?

+4
source share
2 answers

If your project has Front Controller(one file - an entry point),
then you can declare your function in the general namespace in this or necessary ( #require) this file.

-

namespace {
  function s() {
  }
}
+4

, . PHP. function s(..) view::build . - . PHP, :

if (!function_exists('s')) {
    function s(..) ..
}

include ; .

+4

All Articles