Guillaume
Guillaume

Reputation: 217

OOP setting a property through a method within the class?

New to OOP, the idea is to instantiate an object in a class passing two properties in the process and using a method within the class to generate a third property that i would later need to use.

Does this make sense in OOP terms? I would have thought that my dostuff method would create my thirdproperty ready for use for my next methods in the class?

Here's my code:

<?php
class Nameofclass {

public $firstproperty = '';
public $secondproperty ='';
public $thirdproperty ='';


public function __construct ($firstproperty, $secondproperty) {

$this->firstproperty = $firstproperty;
$this->secondproperty = $secondproperty;
}

public function dostuff($firstproperty) {
do a lot of clever stuff here to calculate a $value;
$this->thirdproperty = $value
}

}
$newInstance = new Nameofclass('firstproperty', 'secondproperty');
echo $newInstance->thirdproperty;
?>

What am I doing wrong? My var_dump($newInstance->thirdproperty) returns Null - as initially set i suppose.... slightly confused here?!

Upvotes: 0

Views: 218

Answers (2)

user2762134
user2762134

Reputation:

Why don't you change this

public function __construct ($firstproperty, $secondproperty) {

$this->firstproperty = $firstproperty;
$this->secondproperty = $secondproperty;
}

to

public function __construct ($firstproperty, $secondproperty) {

$this->firstproperty = $firstproperty;
$this->secondproperty = $secondproperty;
$this->doStuff()
}

Upvotes: 1

random_user_name
random_user_name

Reputation: 26180

If you want thirdproperty to be set, then you need to call `dostuff'. One way to accomplish this would be to modify your constructor slightly:

public function __construct ($firstproperty, $secondproperty) {
    $this->firstproperty = $firstproperty;
    $this->secondproperty = $secondproperty;
    $this->dostuff($firstproperty);
}

However, you're missing out on one of the benefits of using OOP by passing that parameter. Instead, you could rewrite dostuff as so:

public function dostuff() {
    // use $this->firstproperty here, since youve already set it instead of passing it into the function
    do a lot of clever stuff here to calculate a $value;
    $this->thirdproperty = $value;
 }

 // Then, your call to dostuff in your constructor could look like this (without the parameter)

public function __construct ($firstproperty, $secondproperty) {
    $this->firstproperty = $firstproperty;
    $this->secondproperty = $secondproperty;
    $this->dostuff();
}

Of course, this all depends on how you intend to use dostuff.

Upvotes: 1

Related Questions