Cha*_*hap 1 oop perl initialization class-variables
我刚刚开始设计一个Perl类,而我很久以前使用OOP的唯一体验就是使用C++.
我需要将一些数据项作为"类变量" - 由所有实例共享.我希望在我第一次实例化一个对象之前对它们进行初始化,并且我希望主程序use MyClass能够为该初始化过程提供参数.
这是一个带有类变量的类的工作示例:
package MyClass;
use strict;
use warnings;
# class variable ('our' for package visibility)
#
our $class_variable = 3; # Would like to bind to a variable
sub new {
my $class = shift;
my $self = { };
bless $self, $class;
return $self;
}
sub method {
my $self = shift;
print "class_variable: $class_variable\n";
++$class_variable; # prove that other instances will see this change
}
Run Code Online (Sandbox Code Playgroud)
这是一个演示:
#!/usr/bin/perl
use strict;
use warnings;
use MyClass;
my $foo = MyClass->new();
$foo->method(); # show the class variable, and increment it.
my $bar = MyClass->new();
$bar->method(); # this will show the incremented class variable.
Run Code Online (Sandbox Code Playgroud)
主程序有没有办法为$ class_variable指定一个值?该值将在主程序的编译时知道.
您也可以通过声明变量"private"来my代替our.在这种情况下,您必须提供一个类方法来初始化它:
my $class_variable = 3;
sub initialize_variable {
my ($class, $value) = @_;
die "Ivalid value $value.\n" unless $value =~ /^[0-9]+$/;
$class_variable = $value;
}
Run Code Online (Sandbox Code Playgroud)
然后在程序中:
'MyClass'->initialize_variable(42);
Run Code Online (Sandbox Code Playgroud)