简体   繁体   中英

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.

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 (ie 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.

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