0

I know that my question is elementary in php, but I can't find any resource to solve it. For sake of simplicity, I brief my problem with a simple code.

I want to separate php and html files. So I creates a file named: view.php

<?php
global $var;

?>
<html>
<body>

<p>
Variable value is:
    <?php  $var ?>
</p>
</body>
</html>

I have another file that uses this template: call.php

<?php



function call(){
global $var;
    $var='111';
    require_once 'view.php';
}


call();

The problem is that the variable does not pass from call.php to view.php.

This code prints a simple html as follow:

Variable value is:

As you can see, the variable value has not printed here.

Please assume that the view.php is a large html template that would be populated with numbers of variables. So, I want to controller and view be as separated as possible.(I don't want to echo html directly)

how can I do that?

I tested the above code, but without success

aminjabari
  • 21
  • 3
  • 2
    You need to echo your variable - `` – DannyXCII Mar 03 '23 at 19:28
  • You also don't need the `global`, since the variable is in scope even without it. (In general, for the sake of sanity, look for solutions that don't depend on global variables.) – Markus AO Mar 03 '23 at 19:38
  • Thank you very much. I can't imagine how I missed this obvious mistake. I was baffled for a day or two. It just solved the problem. Thank you. – aminjabari Mar 03 '23 at 19:39
  • If you wanted to separate HTML entirely into `.html` files, and tokenize variables, then please see my answer to [Simple templating system with {{field}} in PHP](https://stackoverflow.com/a/70863197/4630325). – Markus AO Mar 03 '23 at 19:42
  • Thank you @MarkusAO for your reply. This is an awesome feature than can be implemented for separating html part completely. But in some occasion, maybe the `.php` is the preferred solution. For example, in this project, I use `foreach` in some part of the code to output dynamic view. – aminjabari Mar 03 '23 at 21:16

0 Answers0