如何使用函数 return 的值作为 PHP 中另一个函数的参数?
How to use function return value as parameter for another function in PHP?
我想要一个将 1 个参数作为输入的函数,如果没有传递任何值,它应该将默认值作为另一个函数的输出。我在 PHP 中使用 Class 来实现这一点,但它给了我错误 "Constant expression contains invalid operations"
<?php
class Common
{
public $usrname;
function getLoggedInUser(){
if (ISSET($_SESSION['email'])) {
$this->usrname = ($_SESSION['email']);
return $this->usrname;
}
return false;
}
function getLoggedInUserId($username = $this->usrname){
echo $username;
}
}
并将 class 文件调用为
<?php
include "common.php"
$c = new Common;
$c->getLoggedInUserId();
下面是上述调用的错误显示
Fatal error: Constant expression contains invalid operations
请告诉我如何将函数结果作为参数传递给另一个函数。谢谢
由于默认值必须是常量值,因此您需要这样写...
function getLoggedInUserId($username = null){
if ( $username == null ) {
$username = $this->usrname;
}
echo $username;
}
getLoggedInUserId
用户必须重新定义如下
function getLoggedInUserId($username=""){
if(empty($username)){
echo $this->usrname;
}else{
echo $username;
}
}
将您的函数更改为:
public function getLoggedInUserId($username=""){
$username = ($username == "") ? $this->usrname : $username;
}
我想要一个将 1 个参数作为输入的函数,如果没有传递任何值,它应该将默认值作为另一个函数的输出。我在 PHP 中使用 Class 来实现这一点,但它给了我错误 "Constant expression contains invalid operations"
<?php
class Common
{
public $usrname;
function getLoggedInUser(){
if (ISSET($_SESSION['email'])) {
$this->usrname = ($_SESSION['email']);
return $this->usrname;
}
return false;
}
function getLoggedInUserId($username = $this->usrname){
echo $username;
}
}
并将 class 文件调用为
<?php
include "common.php"
$c = new Common;
$c->getLoggedInUserId();
下面是上述调用的错误显示
Fatal error: Constant expression contains invalid operations
请告诉我如何将函数结果作为参数传递给另一个函数。谢谢
由于默认值必须是常量值,因此您需要这样写...
function getLoggedInUserId($username = null){
if ( $username == null ) {
$username = $this->usrname;
}
echo $username;
}
getLoggedInUserId
用户必须重新定义如下
function getLoggedInUserId($username=""){
if(empty($username)){
echo $this->usrname;
}else{
echo $username;
}
}
将您的函数更改为:
public function getLoggedInUserId($username=""){
$username = ($username == "") ? $this->usrname : $username;
}