Reputation: 578
if i have a function like that:
function ($form, $db) {
$v = count($a);
}
function ($form, $db);
and this code in the same file
<script type="text/javascript">
$(document).ready(function() {
for ($i=0; $i< <?php echo $v-1; ?>; $i++) {//here
}
how can i access the variable $v
? i already know that global variables are generally a bad practice, so what is the alternative?
thanks
Upvotes: 0
Views: 2100
Reputation: 1533
Use return $v
:
function ($form, $db) {
$v = count($a);
return $v;
}
<script type="text/javascript">
$(document).ready(function() {
for ($i=0; $i< <?php echo function( $form , $db )-1; ?>; $i++) {//here
}
Upvotes: 2
Reputation: 1302
Use a class to declare your global variables, so it can give them a context
Example :
class Config {
public static $v;
}
then you can use Config::$v = count(a);
This can be useful if you have more global variables like some configuration parameters that are related to each other and you need to read and write them throughout the application.
If it's not a case and this is just a singular case, than you should consider using the return value.
Upvotes: 0
Reputation: 26
use the function itself, give it a name and use the returned value liks this
function counter($form, $db) {
$v = count($a);
return $v;
}
and on the script file call the function this way
<script type="text/javascript">
$(document).ready(function() {
for ($i=0; $i< <?php echo ($this->counter())-1; ?>; $i++) {//here
}
i hope it helps
Upvotes: 0
Reputation: 1389
Use return on your function to set the value of $v in the global scope. Then the variable will be accessible outside of the function.
<?php
function ttt($form, $db)
{
return count($db);
}
$v = ttt($form, $db);
Now $v is accessible via the global scope.
Also, note that javascript variables do not use the $ prefix, so $i would need to be just i... unless I'm missing something there.
Upvotes: 1
Reputation: 50976
What about basic return
?
function name($form, $db) {
$v = count($a);
return $v;
}
$v = name($form, $db);
Upvotes: 0
Reputation: 50041
Use a global variable; just give it a more descriptive name than $v
so there's no danger of it clashing with something else.
Upvotes: 0