Jump to content

[SOLVED] How to make default argument a class variable?


Jessica

Recommended Posts

This gives a syntax error, but shows what I'm trying to do. If I don't pass it a username and password, I want to use the class values.

function login($username=$this->username, $password=$this->password){
   //mah code!
}

 

My solution:

function login($username=NULL, $password=NULL){
   if($username == NULL){
      $username = $this->username;
   }
   if($password == NULL){   
      $password = $this->password;
   }
   //mah code!
}

 

Anyone know of a better way to do this? Or is the the only way? Obviously it works, I just hate the null checks.

Link to comment
Share on other sites

That's similar to how I always do it....  I usually do something like:

 

class MyClass {
public $this->user;
public $this->pass;

public function __construct($user = false, $pass = false) {
	if($user !== false) $this->user = $user;
	if($pass !== false) $this->pass = $user;
}
}

 

It's the exact same idea, except I'm setting the class variables to the function arguements instead of the other way around.... That way it sets them for hte entire class, and it allows you to access the variables through the class instead of in just that function ;p.

Link to comment
Share on other sites

I'm quite sure there is no other way than the alternative you provided yourself.

 

That's similar to how I always do it....  I usually do something like:

 

class MyClass {
public $this->user;
public $this->pass;

public function __construct($user = false, $pass = false) {
	if($user !== false) $this->user = $user;
	if($pass !== false) $this->pass = $user;
}
}

 

It's the exact same idea, except I'm setting the class variables to the function arguements instead of the other way around.... That way it sets them for hte entire class, and it allows you to access the variables through the class instead of in just that function ;p.

That's exactly the same as she said herself except you used false instead of null.

Link to comment
Share on other sites

I'm quite sure there is no other way than the alternative you provided yourself.

 

That's similar to how I always do it....  I usually do something like:

 

class MyClass {
public $this->user;
public $this->pass;

public function __construct($user = false, $pass = false) {
	if($user !== false) $this->user = $user;
	if($pass !== false) $this->pass = $user;
}
}

 

It's the exact same idea, except I'm setting the class variables to the function arguements instead of the other way around.... That way it sets them for hte entire class, and it allows you to access the variables through the class instead of in just that function ;p.

That's exactly the same as she said herself except you used false instead of null.

 

Actually that's not the same.  That would set the class vars to the args if the args weren't null where as her example would set the args to the class vars if the args were null.

 

 

Anyway, I wasn't sure what you were wanting to do.... I figured you wanted to overwrite the class vars since I don't know why you would want those vars in just one method, but what ever works ;p.

 

I'm pretty sure if you wanted what you said, then your way would be the only one.  Well, if you wanted to automate it more you could do something a bit easier to type out, but it could get kind of blehhh.

 

<?php

class SomeClass {
public $defaults = array(
	'user' => 'Corbin',
	'password' => 'password',
	'someotherthing' => 'foo',
);

public function __construct($args = array()) {
	$args = array_merge($this->defaults, $args);
	print_r($args);
}

}

$sc = new SomeClass(array('user' => 'Hi'));


/*
It would look something like:
Array
(
    [user] => Hi
    [password] => password
    [someotherthing] => foo
)
*/

?>

Link to comment
Share on other sites

Yeah, the null-checks are the best, easiest way I know. Usually, default arguments are only those that are in a constant/global scope.

function login($user="",$pass="") {
if (!$user) $user=$this->user;
if (!$pass) $pass=$this->pass;
}

I usually reserve 'null' for empty objects, arrays, or references. That's just a habit of mine.

Link to comment
Share on other sites

It's not a constructor, it's a function in the class.

 

If I have already created an instance of it, it will have values for those class variables, as set in the constructor. If I want to call the function and use those values, I don't want to pass it anything. If I want to pass it values, they might not need to overwrite the existing class values. So it's the same as wanting to use any other function that has default values.

Link to comment
Share on other sites

It's not a constructor, it's a function in the class.

 

If I have already created an instance of it, it will have values for those class variables, as set in the constructor. If I want to call the function and use those values, I don't want to pass it anything. If I want to pass it values, they might not need to overwrite the existing class values. So it's the same as wanting to use any other function that has default values.

That's fine, it's clarified what I was asking above. The design flaw I was hinting at would have been if you were using the object properties as default values, but never modifying them, just to maintain a "pretty" code layout.

 

In that case, either what you have will be fine, but to be utterly semantic about it explicitly check for a null value:

 

public function something ($var = null)
{
    if (is_null($var)) $var = $this->foo;

    //do something with $var
}

 

P.S. completely off topic.. but I have to ask, what is that above your (someone elses?) shoulder in your avatar?

Link to comment
Share on other sites

Your question has little to do with oop and more to do with setting a variable's value.

 

In my example you will find your answer.

 

i set the class properties to whatever, somehting that you said you've done. if you look at the method in my example , the constructor, you will see that it sets the function's local variables, $con_, based on what is being passed in. the meat in my example is the usage of the ternary operator

 

public function method($user = '', $pass = ''){

$con_user = ($user == '') ? $this->_user : $user;

$con_pass = ($pass == '') ? $this->_pass : $pass;

//do stuff with the local $con_ variables

}

Link to comment
Share on other sites

It has everything to do with OOP, because I wanted to know if it was possible to use $this->value in the arguments of a method in that class. Wouldn't it make sense to be able to use it there? You're in the class at that point.

 

Also, the ternary operator ought to be outlawed. Yes, it's shorter, but it gives no meaning to the code. if else is clear. ?: is not.

And it's still pretty much the same as what I was doing, only using '' instead of NULL.

 

I just wanted to know if there was a way to access the $this->value in the arguments, but unfortunately there is not.

Link to comment
Share on other sites

Yeah, using a variable as a default value for a function/method's property doesnt work. You dont even need to run this example to see that it wont work.

<?php 

$x = 4;
function test($var = $x){
echo $var;
}
test();
?>

 

The ternary operator is one of the best things available in programming :) I also love JavaScript's or for setting variables

 

var x = y || z;  //if y is false, x is set to z

Link to comment
Share on other sites

think about all of the browser inconsistencies. in ie you have a way to do something and in ff and the other browsers there is typically a standard way.

var ajaxTransport = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');

it also works with functionality, this is an example from the mootools library. it says if there is a foreach method in the browser's prototype, use it. if not use this function when foreach is called against an array

 

Array.prototype.forEach = Array.prototype.forEach || function(fn, bind){
for (var i = 0; i < this.length; i++) fn.call(bind, this[i], i, this);
};

 

javascript is easily becoming my favorite language. it's so mysterious

 

Link to comment
Share on other sites

think about all of the browser inconsistencies. in ie you have a way to do something and in ff and the other browsers there is typically a standard way.

var ajaxTransport = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');

it also works with functionality, this is an example from the mootools library. it says if there is a foreach method in the browser's prototype, use it. if not use this function when foreach is called against an array

 

Array.prototype.forEach = Array.prototype.forEach || function(fn, bind){
for (var i = 0; i < this.length; i++) fn.call(bind, this[i], i, this);
};

 

javascript is easily becoming my favorite language. it's so mysterious

 

Time to play pedant again.

 

That will throw exceptions; thus ensuring your code is actually broken; and only works for boolean instances, leaving you open to false passes.

 

The Ternary operator is simply a shortcut "if (expression) {value if true} else {value if false}".. "expression ? value if true : value if false".

Shorter? Yes. Readable? Debatable.

 

Your other example is not unique to JavaScript, and JavaScript is just about the ugliest POS language ever to exist. Of course this is opinions, and no one can prove otherwise to the other so no point arguing over it, but - Have you never wondered why you must implement something as nasty as

var xml = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');

? Answer: Because JavaScript is the least consistent language across browsers. Even CSS is more consistent than JS. :)

 

Link to comment
Share on other sites

Jenk, what will throw exceptions?

 

The more that i learn about JS, the more i love the prototypical approach. However, I do hate everything about actionscript, crazy right? Must be because it is wrapped up in a flash container.

 

I think that the or expression to set a default value is a great time saver. Ternarys are just as great for setting a default value. Its just a style thing like you said.

 

Javascript is not the least consistent language though. You have the standards way, and then  you have the microsoft way. Id say CSS has more loopholes you have to code for each browser than JS does. Listen to Dougless Crockford - the guy behind Yahoo's js, he explains JS' history and how it got to where we are at today. Sure every browser tries to improve the core functionality, that keeps innovation high and pushed into the mainstream, shit if it wasnt for m$ we wouldnt have ajax as it is today, but the battle is basically between IE and everyone else. 

 

http://javascript.crockford.com

http://video.yahoo.com/video/play?vid=111593

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.