Can you pass Objects?

I only know procedural coding and PHP. I want to learn how to program like a professional programmer who knows Python or Java would code. I also want to learn OOP later this year.

One of the things that drives me crazy about my current PHP code is how messy I feel it is to pass data to a function.

For example, let’s say I have several attributes about a user that I need to manipulate. And I have to do this in 10 different scripts.

To make things more efficient, I want to create a function.

But the problem is I have to pass all of the individual attributes back and forth between my scripts and the function. (If you have 20 attributes this is a real PITA.)

In OOP or more sophisticated languages like Python or Java, isn’t there a way to define a “data structure” or “object” that would contain all 20 attributes, and then just pass that single entity to your function?

Right now in several scripts, I capture the user’s Timestamp, IP, Hostname, etc and I’d like to just pass that as a THING instead of having to pass each item separately.

s it stands now, I don’t feel inclined to write functions in my PHP to streamline things, because I feel it just transfers the pain from one thing to another. (Having to write tons of code to pass tons of attributes probably adds more code than I save by creating the new function!!)

Not sure if I am making any sense?!

Yes, it is.


class UserInfo {
	public $ip;
	public $hostname;
	public $timestamp;
}


function foo(UserInfo $user) {
	echo 'IP:' . $user->ip . '<br />';
	echo 'Host:' . $user->hostname . '<br />';
	echo 'Timestamp:' . $user->timestamp . '<br />';
}

$userinfo = new UserInfo;
$userinfo->ip = '2.2.2.2';
$userinfo->hostname = 'example.org';
$userinfo->timestamp = time();

foo($userinfo);

Keep in mind that you can also do this with an Array.

That’s some pretty neat code!

Do you mean using OOP?

Also, can what you did be done with procedural code also?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.