Accessing a Class's Constants

Accessing a class's constants

What you posted should work perfectly:

class Foo
CONSTANT_NAME = ["a", "b", "c"]
end

Foo::CONSTANT_NAME
# => ["a", "b", "c"]

How do methods within a class access class constant variables?

Yes, using self. COURSES is ok. Python has so called "data inheritance". When you write self. COURSES it looks for COURSES in self.__dict__. If the attribute is not found there, self.__class__.__dict__ is searched -- and your class attribute is found. If the attribute is not found is class's __dict__ parent classes are searched.

See also: https://www.python-course.eu/python3_class_and_instance_attributes.php

Accessing class constants from instance stored in another class

Seems like your on an older version of php? PHP 5.3 allows the access of constants in the manner you describe... However, this is how you can do it without that inherent ability:

class ThisClass
{
const FIRST = 'hey';

public function getFIRST()
{
return self::FIRST;
}
}

class ThatClass
{
private $model;

public function setModel(ThisClass $model)
{
$this->model = $model;
}

public function getModel()
{
return $this->model;
}

public function Hailwood()
{
$test = $this->model;
return $test::FIRST;
}
}

$ThisObject = new ThisClass();
echo $ThisObject ->getFIRST(); //returns: hey
echo $ThisObject ::FIRST; //returns: hey; PHP >= 5.3

// Edit: Based on OP's comments
$ThatObject= new ThatClass();
$ThatObject->setModel($Class);
echo $ThatObject->getModel()->getFIRST(); //returns: hey
echo $ThatObject->Hailwood(); //returns: hey

Basically, were creating a 'getter' function to access the constant. The same way you would to externally access private variables.

See the OOP Class Constants Docs: http://php.net/manual/en/language.oop5.constants.php

Ruby: accessing a class constant for instance of class

Now working:

class Foo
MY_CONST = "hello"
ANOTHER_CONST = "world"

def self.get_my_const
const_get("ANOTHER_CONST")
end
end

class Bar < Foo
def do_something
avar = Foo.get_my_const
end
end

Bar.new.do_something # => "world"

Your below part is not correct:

def self.get_my_const
Object.const_get("ANOTHER_CONST")
end

Inside the method get_my_const,self is Foo. So remove Object,it will work..

Accessing a public final constant in another class?

I would, but the Constants class if given by my professor that is not allowing >me to change the Constants class.


There is also this method in his code that may be useful:

public static Constants getInstance() {
if(instance == null)
instance = new Constants();
return instance;
}

Per your edit Constants is a Singleton, so first get the instance and then access the field directly.

INVENTORY_MAX = 100;
Constants consts = Constants.getInstance(); // new Constants();
// ...
if (h <= consts.INVENTORY_MAX)

Ruby: How to access a constant from the class a module is included into

You can reference the class module being included into as self.class and the use const_get or just self.class::CONST, with the latter being slightly faster:

module M
def foo
self.class::CONST
end
end

class A
CONST = "AAAA"
include M
end

class B
CONST = "BBBB"
include M
end

puts A.new.foo # => AAAA
puts B.new.foo # => BBBB

How to access constants from a java class through other variable?

You can use reflection to extract it:

String value = (String) CategoryIDs.class.getField(temp).get(null);

The null argument passed to get signifies this is a static field, and no instance is required in order to get its value.

Note that this technique is very error prone. The code above doesn't contain any error checking or exception handling in order to make it easier to read, but a real application should probably contain them.

Accessing Class Constants from a Class Reference variable in Delphi

An untyped class constant is a normal constant with some scoping added.

A typed class constant is really a class variable that you cannot change.

The problem is that the class variables are not virtual.

Hallvard Vassbotn has written about this issue here: Part 1, Part 2

You cannot access class variables and class constants from a class reference because the language does not have support for virtual class variables.

When you say s:= TClass1.SomeConst the compiler translates this into s:= SomeGlobalButHiddenConst before moving on with the rest of the compilation.

class var and class const are nothing more than syntactic sugar.

As such the link between the class var/const and the actual class only exists during compile-time, it is broken come run-time, much like type-erasure in Java.

RTTI also does not help: Get constant fields from a class using RTTI

I guess if you're using D2007 your only option is to declare a virtual function that returns the constant you want:

Pre D2010 option: virtual method

TParent = class
class function Name: string; virtual;
end;

TChild1 = class(TParent)
class function name: string; override;
....
class function TParent.name: string;
begin
Result:= Self.ClassConst;
end;

class function TChild1.name: string;
begin
Result:= Self.ClassConst; //Silly copy paste solution
end;

This is a sad state of affairs, but I don't see another option.

From Delphi 2010 onwards: use attributes
A better option is to use attributes, these you can access using RTTI:

The following code works:

program TestClassConst;

{$APPTYPE CONSOLE}

uses
SysUtils, rtti;

type

NameAttribute = class(TCustomAttribute)
private
Fname: string;
public
constructor Create(const Name: string);
property Name: string read Fname;
end;

[Name('Base class')]
TParent = class
const
ClassConst = 'BASE CLASS';
private
public
class function Name: string;
end;

[Name('Child 1')]
TChild1 = class(TParent)
const
ClassConst = 'CHILD 1';
end;

[Name('Child 2')]
TChild2 = class(TParent)
const
ClassConst = 'CHILD 2';
end;

TParentClass = class of TParent;
TChildClasses = array[0..1] of TParentClass;

const
ChildClasses: TChildClasses = (TChild1, TChild2);

var
i: integer;
c: TParentClass;
s: string;

{ TParent }

class function TParent.Name: string;
var
Context: TRttiContext;
ClassData: TRttiType;
Attr: TCustomAttribute;
begin
Context:= TRttiContext.Create;
ClassData:= Context.GetType(Self);
try
for Attr in ClassData.GetAttributes do begin
if Attr is NameAttribute then Result:= NameAttribute(Attr).Name;
end;
finally
ClassData.Free;
end;
end;

{ NameAttribute }

constructor NameAttribute.Create(const Name: string);
begin
inherited Create;
FName:= name;
end;

begin
writeln;

writeln('looping through class reference array');
for i := low(ChildClasses) to high(ChildClasses) do begin
c := ChildClasses[i];
writeln(c.ClassName, ' -> ', c.Name);
end;

writeln;

writeln('accessing classes directly');
writeln(TChild1.ClassName, ' -> ', TChild1.Name);
writeln(TChild2.ClassName, ' -> ', TChild2.Name);
readln;
end.


Related Topics



Leave a reply



Submit