从函数外部访问值:js和php生成的值

Hello fellow stackoverflow users, I'm trying again and again to access a variable from outside a function. So I know a variable can't normally be accessed from outside a function, but declaring it first outside the function or returning the variable should give me access, but I can't get it. Here's my code:

<select class='select-style' onchange="selectModel(this)">
  <option></option>
   <?php
    $select_cassetta_name = "select * from cassetta order by cassetta_name ASC";
    $run_cassetta = mysqli_query($con, $select_cassetta_name);
     while($row=mysqli_fetch_array($run_cassetta)){
      $cassetta_id = $row['cassetta_id'];
      $cassetta_name = $row['cassetta_name'];
      $cassetta_price = $row['cassetta_price'];
      echo "<option value='$cassetta_price'>$cassetta_name</option>";
     }
   ?> 
</select>


<div>
  <p id="box"></p>
</div>

<div>
  Sides SUM = <span id="sides_sum"></span> <br>
  Value x Sides = <span id="final_price"></span>
</div>



<script>

  var x;
  var y;
  var z;
  var sum;

  function getSides() {
    var x = parseFloat(document.getElementById("side1").value);
    var y = parseFloat(document.getElementById("side2").value);
    var sum = document.getElementById("sides_sum").innerHTML = x + y;
  }

  function selectModel(selectObject) {
    var z = parseFloat(selectObject.value);
    var cassetta = document.getElementById("box").innerHTML = "You selected value: " + z;
    document.getElementById("final_price").innerHTML = z * sum;
  }

</script>

Do not declare x, y and sum inside function using var. By declaring it using var you are overriding the global variable and creating a local variable. So you are not able to access its value in the other function

function getSides() {
    x = parseFloat(document.getElementById("side1").value);
    y = parseFloat(document.getElementById("side2").value);
    sum = document.getElementById("sides_sum").innerHTML = x + y;
  }

If you redeclare a variable in a function like:

var blub = ..
function xyz() {
   var blub = ....

}

you create a new variable blub in the context/visiblility in the function. The js parser does not know you want to access the first defined blub variable and searches the nearest context for the blub variable and finds the blub inside the function first. So rename the variable inside the function to something like:

var blub = ..
function xyz() {
   var blub2 = ....
   var blub_ = ...
   var blub_inner = 
}

and you can access both

you can use this code:

 function getSides() {
   var x = parseFloat(document.getElementById("side1").value);
  var y = parseFloat(document.getElementById("side2").value);
  var sum = document.getElementById("sides_sum").innerHTML = x + y;
  return sum;
}

function selectModel(selectObject) {
  getSides();
  var z = parseFloat(selectObject.value);
  var cassetta = document.getElementById("box").innerHTML = "You selected value: " + z;
  document.getElementById("final_price").innerHTML = z * getSides();
}