Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables being changed by TeamSpeak API for PHP

I'm developing a tool for a website and I came up with an odd problem, or better, an odd situation.

I'm using the code bellow to retrieve data from the TeamSpeak server. I use this info to build a profile on a user.

$ts3 = TeamSpeak3::factory("serverquery://dadada:dadada@dadada:1234/");
// Get the clients list
$a=$ts3->clientList();
// Get the groups list
$b=$ts3->ServerGroupList();
// Get the channels list
$c=$ts3->channelList();

Now, the odd situation is that the output of this code block:

// Get the clients list
$a=$ts3->clientList();
// Get the groups list
$b=$ts3->ServerGroupList();
// Get the channels list
$c=$ts3->channelList();
echo "<pre>";print_r($a);die();

(Notice the print_r)
Is totally different from the output of this code block:

// Get the clients list
$a=$ts3->clientList();
// Get the groups list
#$b=$ts3->ServerGroupList();
// Get the channels list
#$c=$ts3->channelList();
echo "<pre>";print_r($a);die();

What I mean is, the functions I call after clientList() (which output I store in the variable $a) are changing that variable's contents. This is, they're kind of appending their output to the variable.

I've never learned PHP professionally, I'm just trying it out... Am I missing something about this language that justifies this behavior? If I am, what can I do to stop it?

Thank you all.

like image 516
Daniel Silva Avatar asked Nov 09 '22 01:11

Daniel Silva


1 Answers

You're seeing parts of the "Object" in Object Oriented Programming

$ts3 represents an Object containing all the information needed, along with some methods (or functions) that let you get data from the object. Some of these methods will do different things to the object itself, in order to retrieve additional data needed for a particular method call.

Consider the following simple Object:

  • Bike
    • color
    • gears
    • function __construct($color, $gears)
    • this.color = $color; this.gears = $gears
    • function upgrade()
    • this.headlight = true; this.gears = 10;

Now, when you first create it, it only has two properties:

$myBike = new Bike('red',5);
// $myBike.color = 'red';
// $myBike.gears = 5;

...but once you upgrade, properties have changed, and new ones are added.

$myBike->upgrade();
// $myBike.color = 'red';
// $myBike.gears = 10;
// $myBike.headlight = true;

Objects usually pass references rather than copying data, in order to save memory.

...but if you want to make sure that you're getting a copy that won't change (i.e. does not use data references to the $ts3 object), clone the variable.

$a = clone($ts3->clientList());

Be warned, this will effectively double the memory and processor usage for that variable.

like image 197
Tony Chiboucas Avatar answered Nov 15 '22 12:11

Tony Chiboucas