开发者

How can I make a function in php that will have signature void myFunction()

开发者 https://www.devze.com 2023-04-12 17:19 出处:网络
By default php returns NULL for function that doesn\'t do anything. For example: 1 <?php 2 3 function foo() {

By default php returns NULL for function that doesn't do anything.

For example:

1 <?php
2 
3 function foo() {
4     // Nothing here
5 }
6
7 var_dump(foo()开发者_如何学JAVA); // the result will be NULL

I'm trying to implement an function that will have direct output and i don't need to return anything from inside the function, i what to obtain something like:

void var_dump()// it just only dumps information.

My function will generate a image but will not return any information. The image will be generated, after processing, using ImageJpeg($image) inside the function. The signature in php manual for imageJpeg is:

imagejpeg — Output image to browser or file

in this way I'll have output image and NULL returned from function. How can i avoid that. How can i obtain ONLY output image?

Thank you in advance.


The PHP equivalent of a void function foo() is a regular function that simply has no return statement. Whether this function outputs anything or not is completely independent of that. A function may output something in any variety of ways and return a value, or either or neither. In concrete terms, this is a function with no return value which outputs an image:

function foo() {
    ...
    imagejpg(...);
}

foo();

What you may be confusing here is the difference between a return value and output. The output is what the program finally outputs to the user/stout/php://output. A function return value is what the function returns to the caller.

function foo() {
    echo 'Hello World';
    imagejpg(...);
    return 'foo';
}

$bar = foo();

This function visibly prints "Hello World" on your screen followed by some binary image. The function returns the string 'foo' and the variable $bar now holds 'foo', but this is not output.


A function that directly outputs content can be done via echo, print, etc. For example:

function sayHello($name = null) {
    if ($name === null) {
       echo "Hello!";
    } else {
       echo "Hello {$name}";
    }
}

sayHello("Fred"); // outputs: Hello Fred
sayHello();       // outputs: Hello!
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号