Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to a pass function to an included file?

Tags:

php

I have a view class with a function to build the 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 a view 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 the function s In each view file but I really dont want to have to do that.

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

I could call the static function in the view directly but even that is more long winded than I'd like:

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

Is this possible? or any other suggestions?

like image 536
andrew Avatar asked Feb 12 '23 13:02

andrew


1 Answers

If your project has a Front Controller (one file - entry point),
then you can to declare your function in common namespace in this or required(#require) by this file.

Common namespace is code without namespace or

namespace {
  function s() {
  }
}
like image 58
vp_arth Avatar answered Feb 14 '23 03:02

vp_arth