2013-08-27 272 views
0

我新的PHP和最近发现做“if语句”,使拥有大量HTML更容易集成的另一种方式:呼叫功能

<?php if(something): ?> 

All the HTML in here 

<?php endif; ?> 

现在我想知道如果一类似的事情可以用功能来完成?我已经声明了一个创建一些变量的函数,现在我想调用该函数并在我的HTML的一部分中使用这些变量。

E.g.

function test(){ 
    $test1 = 'test1'; 
    $test2 = 'test2'; 
} 

test(); 
<div><?php $test1; ?></div> 
<div><?php $test2; ?></div> 

上述不会工作,因为函数中创建的变量不是全局的,我不想让它们成为全局变量。该函数在一个单独的php文件中声明。

我最初的搜索没有发现任何东西。

+0

是否有你不想让他们全球的理由吗? –

+0

如果你不想让全局变量,你需要返回它们,没有其他方式让他们离开函数。但从你的代码看来,全局是最好的方法 – x4rf41

+0

使函数返回值,然后做

Dexa

回答

2

嗯..使用数组?

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> 

或者你可以做它在客观还挺-Y方式:

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> 
+0

是的,这是东西。 – Coop