Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you access Object properties from within an object method? [closed]

Tags:

java

oop

php

theory

What is the "purist" or "correct" way to access an object's properties from within an object method that is not a getter/setter method?

I know that from outside of the object you should use a getter/setter, but from within would you just do:

Java:

String property = this.property; 

PHP:

$property = $this->property; 

or would you do:

Java:

String property = this.getProperty(); 

PHP:

$property = $this->getProperty(); 

Forgive me if my Java is a little off, it's been a year since I programmed in Java...

EDIT:

It seems people are assuming I am talking about private or protected variables/properties only. When I learned OO I was taught to use getters/setters for every single property even if it was public (and actually I was told never to make any variable/property public). So, I may be starting off from a false assumption from the get go. It appears that people answering this question are maybe saying that you should have public properties and that those don't need getters and setters, which goes against what I was taught, and what I was talking about, although maybe that needs to be discussed as well. That's probably a good topic for a different question though...

like image 444
cmcculloh Avatar asked Aug 01 '08 16:08

cmcculloh


People also ask

How do you access the properties of objects in typescript?

To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .

How do you access the properties of an object with a variable?

Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .


1 Answers

This has religious war potential, but it seems to me that if you're using a getter/setter, you should use it internally as well - using both will lead to maintenance problems down the road (e.g. somebody adds code to a setter that needs to run every time that property is set, and the property is being set internally w/o that setter being called).

like image 179
Greg Hurlman Avatar answered Sep 21 '22 15:09

Greg Hurlman