简体   繁体   中英

PHP interpreter behaving weird

I found this weird behaviour on classes. Is this a PHP Bug ?

<?php
class A
{

public function disp1()
{
echo "1";

}

public function disp3()
{
echo "3";
}

}

$a = new A;
echo $a->disp1()." 2 ".$a->disp3();

Expected Result

1 2 3

Actual Result

13 2

You are echo ing what is already echo 'd. Those two methods are run before the echo is rendered. So the echo s in each method are run first, then the echo outside your class is run. The only thing it will render, however, is 2 .

To get your expected result you need to return the values from each method:

class A {
    public function disp1() {
        return "1";
    }
    public function disp3() {
        return "3";
    }
}

$a = new A;
echo $a->disp1()." 2 ".$a->disp3();

It's because you have echo in methods, not return. So first it will echo 1 then 3, then the result which is now " 2 " because the methods return NULL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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