我如何从函数内部获取价值?
是否可以在函数内部获取这些值并在函数外部使用这些值 这是我的代码:
<?
function expenditure () {
$totalexpenditure = $sum1 + $sum2;
}
function income () {
totalincome = $sum1 + $sum2;
}
$profit = $totalincome - $totalexpenditure;
?>
现在我的问题是如何获得总收入和总支出的值? 我正在学习 php,所以请帮助我。
Is it possible to get those values inside of function and use those outside of function
here is my code:
<?
function expenditure () {
$totalexpenditure = $sum1 + $sum2;
}
function income () {
totalincome = $sum1 + $sum2;
}
$profit = $totalincome - $totalexpenditure;
?>
now my question is how can i get value of totalincome and toatalexpenditure ?
i am learning php alos new in php so please help me guys.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
返回语句
return statement
您的代码是错误的,因为:
$profit
将始终为0
(零)。解决方案共有三个:
解决方案编号。 1:
然后你可以像这样使用它:
解决方案编号。 2:
然后你就可以像这样使用它:
解决方案编号。 3:(避免使用!)
然后你就这样使用它:
我希望你明白,为什么解决方案没有。 3 是一个坏主意(因为通常使用全局变量将某些东西传递给函数是坏主意)。
Your code is wrong, because:
$profit
will be always0
(zero).The solutions are three:
Solution no. 1:
And then you can use it like that:
Solution no. 2:
and then you can use it like that:
Solution no. 3: (avoid using!)
And then you use it like that:
I hope you see, why the Solution no. 3 is such a bad idea (as generally using
global
variables to pass something to function is bad idea).这涉及到您稍后可能会遇到的另一个问题。如果您想在函数中传递 2 个变量并更改它们的值,该怎么办?
您将得到此输出
$x
和$y
参数本身不是变量,而是引用(由&
定义)对于传递的变量,如果您需要在内部更改外部变量的值,这会很有帮助。链接了解更多 http://php.net/manual/en/language.references .pass.php
This relates to another problem, that you may face at a later stage. What if you wanted to pass 2 variables in a function and change both their values.
You will get this as an output
The
$x
and$y
parameters are not a variable themselves, but a reference (defined by&
) to the variables passed through, this is helpful if you require to change the values external variables internally.Link to understand more http://php.net/manual/en/language.references.pass.php