Constructor (object-oriented programming): Difference between revisions

Content deleted Content added
Syntax: PHP 7 construct name info
Loudogni (talk | contribs)
Perl 6: Minor corrections
Line 549:
=== Perl 6 ===
 
With Perl 6, even more boilerplate can be left out, given that a default ''new'' method is inherited, attributes can be specified, as well as whether they can be set, reset, or are required. In addition, any extra constructor functionality can be included in a ''BUILD'' method which will get called to allow for custom initialization. A ''TWEAK'' method can be specified to post-process any attributes already (implicitelyimplicitly) initialized.
 
<source lang="perl6">
class Person {
has Str $.first-name is required; # first name (a string) can only be set at construction time (the . means "public")
# construction time (the . means "public").
has Str $.first-name is required;
has Str $.last-name is required; # last name (a string) can only be set at construction time (a ! would mean "private")
# construction time (a ! would mean "private").
has Str $.last-name is required;
has Int $.age is rw; # age (an integer) can be modified after
# age (Integer) can be modified after # construction ('rw'), and is not required
# to be passed to be constructor.
# during the object instantiation.
has Int $.age is rw;
# Create a 'has-age' method which returns true if age has been set
# create a 'full-name' method which returns the person's full name.
method has-age { self.age.defined }
# this method can be accessed outside the class.
method full-name { $!first-name.tc ~ " " ~ $!last-name.tc }
 
# Createcreate a 'has-age' method which returns true if age has been set.
# Check custom requirements
# this method is used only inside the class so it's declared as "private"
# by prepending its name with a !
method !has-age { self.age.defined }
# Checkcheck custom requirements
method TWEAK {
if $self.has_age!has-age && $self.!age < 18 { # no under 18s18
die "No person under-18 Persons18";
}
}
Line 572 ⟶ 579:
</source>
 
In both cases theThe Person class is instantiated just like in Perl 5this:
<source lang="perl6">
my $p0 = Person.new( first-name => 'Sam', last-name => 'Ashe', age => 42 );
use Person;
my $pp1 = Person.new( first-name => 'Samgrace', last-name => 'Ashehopper', age => 42 );
say $p1.full-name(); # OUTPUT: «Grace Hopper␤»
</source>
 
ButAlternatively, Perlthe 6named alsoparameters hascan anotherbe way of specifying named parametersspecified using the colon-pair syntax in Perl 6:
<source lang="perl6">
my $pp0 = Person.new( :first-name<Sam>, :last-name<Ashe>, :age(42) );
my $p1 = Person.new( :first-name<Grace>, :last-name<Hopper> );
</source>
 
Line 588 ⟶ 597:
my $last-name = "Ashe";
my $age = 42;
my $pp0 = Person.new( :$first-name, :$last-name, :$age );
</source>