Jump to content

Add a variable to a class instance at runtime: Difference between revisions

→‎{{header|Perl 6}}: show shorthand mixin
(→‎{{header|Perl 6}}: Add Perl 6 example)
(→‎{{header|Perl 6}}: show shorthand mixin)
Line 420:
my $that = $object.clone; # instantiate a new Bar derived from $object copying any variables
say $that.foo; # 5 - value from the cloned object</lang>
That's what's going on underneath, but often people just mix in an anonymous role directly using the <tt>but</tt> operator. Here we'll mix an attribute into a normal integer.
<lang perl6>my $lue = 42 but role { has $.answer = "Life, the Universe, and Everything" }
 
say $lue; # 42
say $lue.answer; # Life, the Universe, and Everything</lang>
On the other hand, mixins are frowned upon when it is possible to compose roles directly into classes (as with Smalltalk traits), so that you get method collision detection at compile time. If you want to change a class at run time, you can also use monkey patching:
 
<lang perl6>use MONKEY_TYPING;
augment class Int {
method answer { "Life, the Universe, and Everything" }
}
say 42.answer; # Life, the Universe, and Everything</lang>
This practice, though allowed, is considered to be Evil Action at a Distance.
 
=={{header|PHP}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.