Connecting Tech Pros Worldwide Forums | Help | Site Map

Passing variables to a class

vern
Guest
 
Posts: n/a
#1: Sep 19 '08
Greetings, how would I pass variables that are outside a class ... to
a class? Such as ...

$variable_one = 1;
$variable_two = 2;

class this_is_a_class {

public $variable_one;
public $variable_two;

}

I want to pass both variables to the class this_is_a_class. How would
I go about doing this?

FutureShock
Guest
 
Posts: n/a
#2: Sep 19 '08

re: Passing variables to a class


vern wrote:
Quote:
Greetings, how would I pass variables that are outside a class ... to
a class? Such as ...
>
$variable_one = 1;
$variable_two = 2;
>
class this_is_a_class {
>
public $variable_one;
public $variable_two;
>
}
>
I want to pass both variables to the class this_is_a_class. How would
I go about doing this?
One way is to use setter functions.

Study this and you will begin to grasp a basic understanding of Classes.

http://www.php.net/manual/en/language.oop5.php
Jerry Stuckle
Guest
 
Posts: n/a
#3: Sep 19 '08

re: Passing variables to a class


vern wrote:
Quote:
Greetings, how would I pass variables that are outside a class ... to
a class? Such as ...
>
$variable_one = 1;
$variable_two = 2;
>
class this_is_a_class {
>
public $variable_one;
public $variable_two;
>
}
>
I want to pass both variables to the class this_is_a_class. How would
I go about doing this?
>
Setter functions and/or a constructor.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================

sheldonlg
Guest
 
Posts: n/a
#4: Sep 19 '08

re: Passing variables to a class


vern wrote:
Quote:
Greetings, how would I pass variables that are outside a class ... to
a class? Such as ...
>
$variable_one = 1;
$variable_two = 2;
>
class this_is_a_class {
>
public $variable_one;
public $variable_two;
>
}
>
I want to pass both variables to the class this_is_a_class. How would
I go about doing this?
The whole idea behind OOP is that you can't do that. All you can do is
to have the instance of the class obtain the value on its own. This is
done with a mutator function where the instance of the class goes and
obtains the value and then sets that value in its own data set. Your
example:

Inside the class TheClass:

private $variable_one;
private $variable_two;

public function setVariableOne($val) {
$this->variable_one = $val;
}

Outside the class TheClass;

$obj = new TheClass();
$obj->setVariableOne('foo');

The variables $variable_one and $variable_two are members of the class
and are NOT exposed to the outside world except my mutator functions of
set and get. You can't just set them or get them by a direct call. You
MUST have those helper mutator functions.
Closed Thread