简体   繁体   English

PHP-从类中回显数组值

[英]PHP - Echo an array value from a class

I have the following PHP code 我有以下PHP代码

<?php
class SimpleEmailServiceMessage
{
    public function properNames($formValue) {
    $formValue = strtolower($formValue); //Make all letters small case
    $formValue = ucwords($formValue); //Make all first letters capital
    $formValue = str_replace('','',$formValue); //Remove extra spaces

    if(is_numeric($username)) {
      $error[] = 'The name is invalid';
    }
    return $error;
    return $formValue;
    }
}

$username = 'john doe';

$m = new SimpleEmailServiceMessage();
echo $m->properNames($username);

foreach($error as $result) {
    echo $result . '<br>';
}
?>

I am managing to output $username, but I am not managing to output $error[] if it is a number. 我正在设法输出$ username,但是如果它是一个数字,我就不会输出$ error []。 $error[] in my case is an array as different classes will have an error. 在我的情况下,$ error []是一个数组,因为不同的类会有错误。

The current code is telling me Array Warning: Invalid argument supplied for foreach() in /web/com/140895582016925/main.php on line 22 which is for foreach($error as $result) { 当前代码告诉我Array Warning: Invalid argument supplied for foreach() in /web/com/140895582016925/main.php on line 22foreach($error as $result) {

The error message say it all: your $error is NOT an array. 错误消息说明了一切:$ error不是数组。

Take a look at the is_numeric() validation part of your code. 看一下代码的is_numeric()验证部分。
You have an error there. 那里有错误。
is_numeric() needs an argument. is_numeric()需要一个参数。
In your case i think you need to: 就您而言,我认为您需要:

if ( is_numeric($formValue ) )
{
// execute if condition
}

try this 尝试这个

   <?php
class SimpleEmailServiceMessage
{
    public $error;

    public function properNames($formValue) {
    $formValue = strtolower($formValue); //Make all letters small case
    $formValue = ucwords($formValue); //Make all first letters capital
    $formValue = str_replace('','',$formValue); //Remove extra spaces

    if(is_numeric($formValue)) {
      $this->error[] = 'The name is invalid';
    }
    return $formValue;
    }
}

$username = 'john doe';

$m = new SimpleEmailServiceMessage();
echo $m->properNames($username);

if(isset($m->error))
{
  foreach($m->error as $result) {
     echo $result . '<br>';
  }
}
?>

Demo 演示

Try to use assignment: 尝试使用分配:

$error = $m->properNames($username);

instead of echo ing: 而不是echo

echo $m->properNames($username);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM