0

This is what I want to do:

class Contacts {

    private $_plural = 'contacts';
    private $_single = 'contact';
    private $_factory = 'contactfactory';
    private $_model = 'contact_model';

    private $_idname = $_plural . "Id";

    function a($$_idname = 0) {

    }
}

These two lines:

private $_idname = $_plural . "Id";

and

function a ($$_idname = 0) {

aren't working. Why? And how can I fix this?

EDIT

About the function argument:

If $_idname = "contactId" I want the argument to be $contactId. That's why I have two dollar signs there. This might be not the correct way to handle this, but this is what I want to accomplish.

Angelo A
  • 2,744
  • 6
  • 28
  • 37

2 Answers2

2

According to PHP's documentation, you must initialize a class attribute with a constant value:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

A fix for this would be using a class constructor:

function __construct() {
    $this->_idname = $this->_plural . "Id";
}

Also, you can't use dynamic variable names on functions or methods:

Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Diego Bauleo
  • 681
  • 3
  • 12
  • I indeed thought about doing it the way in the constructor, but I thought it might be cleaner and clearer doing it there where I declare the class variables. Thanks for the information anyways. – Angelo A Mar 12 '15 at 22:44
1

You could change

private $_idname = $_plural . "Id";

to

private $_idname;
public function __construct(){
  $this->_idname = $this->_plural.'Id';
}

first.

Not seeing enough in function a. Probably more like:

public function a($really = 'What is the point of those underscores?'){
  ${$this->_idname} = $really; // local $contacts var holds $really
}

I'm really guessing that you want to have a method that will automatically change your instantiated Object property. You don't need a variable variable for that. If you want to affect a variable which you are passing as an argument it's &$yourVar. There is no need to pass a property of an instantiated Object to its own method, since you already have access to it within the method with $this->yourVar.

StackSlave
  • 10,613
  • 2
  • 18
  • 35
  • $this->_plural, doesn't work either. I get the error: Parse error: syntax error, unexpected '$this' (T_VARIABLE) about the function variable. I'll edit my question – Angelo A Mar 12 '15 at 22:39