stack
stack

Reputation: 10228

Why my code doesn't work correctly when I put it into function?

I have a script named MakeAvatar.php which generates a avatar (something like stackoverflow's avatars) based on two parameters:

Aslo I have this folder-structure:

\out
    MakeAvatar.php
\root
    \classes
        classname.php
    \img
        /* where images (avatars) are saved */

Now, there is two cases:

classname.php

// these two parameters are changeable and these are just as an example
$size = 100;
$hash  = 'somettext';
require("../out/MakeAvatar.php");

Output:

enter image description here


classname.php

class classname{
    function index() {
        // these two parameters are changeable and these are just as an example
        $size = 100;
        $hash  = 'somettext';
        require("../out/MakeAvatar.php");
    }
}

$obj = new classname;
$obj->index();

Output:

enter image description here


What's wrong with it? And how can I fix it? Why when I warp MakeAvatar.php into a function, id doesn't create a correct avatar?

Here is the errors I get when I put MakeAvatar.php into function.

Upvotes: 1

Views: 104

Answers (1)

Victor Smirnov
Victor Smirnov

Reputation: 3780

I have checked the code for the MakeAvatar.php file and seems like the issue is in the following code

/* generate sprite for corners and sides */
function getsprite($shape,$R,$G,$B,$rotation) {
    global $spriteZ;

The variable $spriteZ is defined in line #327 in the file. But when you include the file inside function this variable is not created as global variable but this is a variable inside a function. Check the variable scope manual.

This means that inside getsprite) function the variable $spriteZ has null value because when the file is included inside a function there is no such global variable $spriteZ (it is not initialized as global variable). This is why the call to function imagecreatetruecolor() fails with error

Warning: imagecreatetruecolor(): Invalid image dimensions in C:\xampp\htdocs\inaccessible\identicon.php on line 7

I suggest to modify getsprite() and getcenter() functions and provide this variable as a parameter. Cause global variables might be very confusing.

p.s. The code architecture in general is not optimal but I guess this is out of scope of the question.

Upvotes: 1

Related Questions