473,657 Members | 2,530 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Are setter methods needed when constructor sets properties?

290 Contributor
Hi,
I have just started learning OOP
and have a couple of questions.

Is it correct to say that if I write a constructor method for my class
then I will not need to use he set method to add values to properties ?

i.e. with this:

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. class person {
  3.   var $name;
  4.   var $sp_number; 
  5.       public $height;
  6.       protected $social_insurance;
  7.  
  8. function __construct($persons_name) {
  9.     $this->name = $persons_name;
  10.   }
  11.  
  12. function get_name() {
  13.     return $this->name;
  14.   }
  15.  
  16. } // end class
  17. ?>
  18.  

this will not be needed:

Expand|Select|Wrap|Line Numbers
  1.  function set_name($new_name) {  
  2.    $this->name = $new_name;            
  3.   }
  4.  
because in my html I will use this:

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $stefan = new person("Stefan Mischook");             
  3.  
  4. echo "Stefan's full name: " . $stefan->get_name()."<br>";
  5. ?>
True - or have I got things mixed up ?
Jan 25 '09 #1
9 3228
Markus
6,050 Recognized Expert Expert
@jeddiki
You may later want to change the person's name. Maybe he/she gets married and take's the other person's name? Should always have getter and setter methods, I believe.

Also, could you please read your Personal Messages.

Thanks,
Markus.
Jan 25 '09 #2
jeddiki
290 Contributor
Following on from that question is another
basic newbie one:

Again using this class:

class_lib.php
Expand|Select|Wrap|Line Numbers
  1. class person {
  2.   var $name;
  3.   var $sp_number; 
  4.   public $height;
  5.   protected $social_insurance;
  6.  
  7.  
  8.   function __construct($persons_name) {
  9.     $this->name = $persons_name;
  10.   }
  11.  
  12.  
  13.   function set_name($new_name) {  
  14.    $this->name = $new_name;            
  15.   }
  16.  
  17.   function get_name() {
  18.     return $this->name;
  19.   }
  20.  
  21. } // end class
  22.  
To apply values to the name property I use this:

<?php
$stefan = new person("Stefan Mischook");
?>
How do I add a value to the $sp_number ?

I guess that I can not use the constructor again
so do I add this to class_lib.php ?

Expand|Select|Wrap|Line Numbers
  1.   function set_sp_number($new_sp_number) {  
  2.    $this->sp_number = $new_sp_number;            
  3.   }
  4.  
and then use it like this ?

Expand|Select|Wrap|Line Numbers
  1. $stefan->set_sp_number(8872);
Any explaination would be greatly appreciated :)
Jan 25 '09 #3
Markus
6,050 Recognized Expert Expert
You can pass multiple arguments to a method.

Expand|Select|Wrap|Line Numbers
  1.  
  2. class Example
  3. {
  4.  
  5.     public $firstName;
  6.     public $lastName;
  7.  
  8.     // Constructor
  9.     function Example($first, $last)
  10.     {
  11.         $this->firstName = $first;
  12.         $this->lastName = $last;
  13.     }
  14.  
  15. }
  16.  
  17. $ex = new Example("John", "Dorian");
  18.  
  19.  
Jan 25 '09 #4
jeddiki
290 Contributor
Thats fine but what if I need to add the $lastName at a
later date ( eg when they fill out a profile form).

How do I add the $lastName then - I guess a should not
use :

Expand|Select|Wrap|Line Numbers
  1. $ex = new Example( , "Dorian");
or could I ?
Jan 25 '09 #5
Markus
6,050 Recognized Expert Expert
You can set default values for arguments on methods. So you can provide either a first name and a last name, or just a first name.

Expand|Select|Wrap|Line Numbers
  1. function Example($first, $last = "")
  2. {
  3.     ....
  4. }
  5.  
And you could set the last name later, with a setter method.

Expand|Select|Wrap|Line Numbers
  1. $ex->set_lastName("Dorian");
  2.  
You don't call your constructor after you have initialised the class, i.e after you have done $ex = new Example().
Jan 25 '09 #6
Dormilich
8,658 Recognized Expert Moderator Expert
@jeddiki
correct, PHP will throw an error in this case.

to add the name either use the setter method or set the property directly, if it is defined public.
Expand|Select|Wrap|Line Numbers
  1. $ex->lastName = "Dorian";
note: the var keyword is not encouraged in PHP 5, it is simply kept for compatibility reasons towards PHP 4
Jan 25 '09 #7
jeddiki
290 Contributor
Do you mean the var that I put in my class_lib.php ?

Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. class person {
  4.   var $name;
  5.     var $sp_number; 
  6.       public $height;
  7.       protected $social_insurance;
  8.  

If so how should I be writing it in that class definition ?

BTW I am reading through the PHP 5 Power Programming by Andi Gutmans
so hopefully I'll get better at this ;)
Jan 25 '09 #8
Dormilich
8,658 Recognized Expert Moderator Expert
@jeddiki
a) yes

b) that depends on the usage, possible values
  • public (external read/write access)
  • protected (internal access across inheritance)
  • private (access only inside the defining class)
static, const and read-only are covered later
Jan 25 '09 #9
Markus
6,050 Recognized Expert Expert
You should declare variables as protected, private or public (usually).

So don't use the 'var' keyword, but any of the above. It's not going to give you any trouble, though.


-_- nvm.
Jan 25 '09 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

125
7155
by: Raymond Hettinger | last post by:
I would like to get everyone's thoughts on two new dictionary methods: def count(self, value, qty=1): try: self += qty except KeyError: self = qty def appendlist(self, key, *values): try:
9
1592
by: Jimmy Cerra | last post by:
I am a little confused how the memory for objects is allocated in JavaScript. David Flanagan, in "JavaScript: The Definitive Guide," states that each property of a class takes up memory space when instantiated. So space is created for aMethod three times in this example: // Example 1 function aMethod() {/*stuff*/}; function AClass() { /*stuff*/
5
1656
by: Flipje | last post by:
In my view, there is a major drawback to using attributes: the getter and the setter have identical protection levels. But I usually want the getter to be public and the setter to be protected or even private. Example: I would have liked this to be possible: int Thingy { public get { return mThingy; } private set { mThingy = value; }
8
6580
by: Herve Bocuse | last post by:
Hi, I'm just wondering what are the guidelines for using a Property or a pair of get/set methods related to a member variable ? What do yu guys do ? Thank you Herve
10
1752
by: John | last post by:
Trying to find out what is essential / optional, I made an extremely simple Class and Module combination to add two numbers. (see below) It appears that an empty constructor is needed n order to work right, although I quite don't see what is does in addition to the 2nd constructor. Also, the example works fine without message calls in either constructor (the numerical answer is still there and correct!). I exected it to no longer work...
12
5538
by: Andrew Poulos | last post by:
With the following code I can't understand why this.num keeps incrementing each time I create a new instance of Foo. For each instance I'm expecting this.num to alert as 1 but keeps incrementing. Foo = function(type) { this.num = 0; this.type = type this.trigger(); } Foo.prototype.trigger = function() {
3
1771
by: rickeringill | last post by:
Hi comp.lang.javascript, I'm throwing this in for discussion. First up I don't claim to be any sort of authority on the ecmascript language spec - in fact I'm a relative newb to these more esoteric uses (abuses?) of the language. I've been working from the oft quoted resource http://www.crockford.com/javascript/private.html. During my first serious attempt at using the knowledge acquired from this page, I ran up against the problem...
3
99384
by: Martin Pöpping | last post by:
Hello, I´m coming from the Java World. Here Programmers often use (like in C++?) getter and setter methods. F.e.: class Mirror{ private int width_;
26
2527
by: Cliff Williams | last post by:
Can someone explain the pros/cons of these different ways of creating a class? // 1 function myclass() { this.foo1 = function() {...} } // 2a
0
8413
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8842
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8740
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8513
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7352
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6176
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1733
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.