1

I have a problem with the constant __NAMESPACE__ in PHP, whose value of which may contain backslash. If I pass this value directly to Javascript within a website, Javascript interprets this backslash as a control character and thus takes an incorrect value.

Example:

<?php
    namespace tier1\tier2;
?>
<!DOCTYPE html>
...
<script>
    let var = "<?php echo __NAMESPACE__; ?>";
</script>
...

When the PHP compiler passes the source code, it says in the script line

    let var = "tier1\tier2";

what's right. But Javascript interprets the backslash and sets the value of var into "tier1   ier2" ( \t is interpreted as a tab ). Because Javascript makes no difference how a constant string is framed ("String", 'String', `String`), the escaped characters will be always interpreted.

Is there an easy way to configure the result of the PHP constant __NAMESPACE__ to contain shlashes instead of backslashes? Because each handover with

    let var = "<\?php ​​echo str_replace('\\\\', '/', \_\_NAMESPACE__); ?>";

is a) very cumbersome and b) it puts a useless load on the CPU.

P.S. I am working with PHP version 7.3.15 on a Windows system.

Kira-Bianca
  • 59
  • 1
  • 2
  • What about using, underscores instead of backslashes when you pass to the javascript? perhaps user [String.raw](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw)? or model the namespaces as objects, `tier1 = { tier2: { tier3: { /* ... */ } } }` – admcfajn Sep 18 '20 at 17:50
  • `let var = = json_encode(__NAMESPACE__) ?>;` – miken32 Sep 18 '20 at 23:54

0 Answers0