Filling out a new instance of a class, is this the only way (constructor
injection)
I have a class of Person
class Person
{
public $Name;
public $Age;
}
If I want to create a new Person and fill in his properties, I usually
implement a construct and use that to fill the instance in.
class Person
{
public $Name;
public $Age;
function __Construct( $params )
{
$this->Name = ( isset( $params[ "Name" ] ) ) ? $params[ "Name" ] :
null;
$this->Age = ( isset( $params[ "Age" ] ) ) ? $params[ "Age" ] : null;
}
}
$person = new Person( array(
"Name" => "Michael",
"Age" => "25"
) );
Is there a better way of doing this?
For example, getters and setters in C#?
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
new Person {
Name = "Michael",
Age = 25
}
The idea of knowing is to extend my knowledge. I am aware of magic methods
but I really would like to see an example of exactly what I have
represented as I get quite confused.
EDIT://
Here is another example that clarifies why getters and setters are very
much invited into PHP.
<?php
abstract class DataIdentity
{
public $Id;
}
class Animal extends DataIdentity
{
public $Type;
public $Size;
}
class Dog extends Animal
{
private $BarkVolume;
public GetBarkVolume()
{
return $BarkVolume * $this->Size;
}
}
$animals = array(
new Dog();
)
?>
Without them, I must reference all properties across 3 entities in the dog
constructor, then do the same in another type of class... I'm aware of
other work arounds but the point still remains, this has been a big learn
for me. Thanks etc.
No comments:
Post a Comment