Reputation: 14398
I'm new to PHP and recently discovered another way of doing 'if statements' to make integration with large amounts of HTML easier:
<?php if(something): ?>
All the HTML in here
<?php endif; ?>
Now I'm wondering if a similar thing can be done with functions? I've declared a function that creates some variables and now I want to call that function and use those variables in parts of my HTML.
E.g.
function test(){
$test1 = 'test1';
$test2 = 'test2';
}
test();
<div><?php $test1; ?></div>
<div><?php $test2; ?></div>
The above won't work because the variables created in the function are not global and I don't want to make them global. The function is declared in a separate php file.
My initial searches didn't turn up anything for this.
Upvotes: 0
Views: 92
Reputation: 6524
Ummm.. Using an array?
function test(){
$result = array(); // Empty array
$result['test1'] = 'test1';
$result['test2'] = 'test2';
return $result; // Return the array
}
$result = test(); // Get the resulting array
<div><?php $result['test1']; ?></div>
<div><?php $result['test2']; ?></div>
Or you could do it in kinda objective-y way:
function test(){
$result = new stdClass; // Empty object
$result->test1 = 'test1';
$result->test2 = 'test2';
return $result; // Return the object
}
$result = test(); // Get the resulting object
<div><?php $result->test1; ?></div>
<div><?php $result->test2; ?></div>
Upvotes: 2
Reputation: 623
You can use them if you return;
them. Check
http://php.net/manual/en/function.return.php for more details of the return;
sintax.
Upvotes: 1