1

I'm working with Personal Weather Station Upload Protocol on Weather Underground. I am creating a class with all the attributes that a PWS may contain, and then just use the http_build_query() to create my request.

My problem is: the Weather Underground has two fields with invalid identifiers names for PHP. Check out:

AqUV-AETH  -UV-AETH (second channel of Aethalometer at 370 nm) UG/M3
AqPM2.5 - PM2.5 mass - UG/M3 

My class can not contain these property names, what can I do?

Erro:

class Foo {
    public AqUV-AETH = null;
    public AqPM2.5 = null;
}
PHPJungle
  • 502
  • 3
  • 16
Renato Tavares
  • 201
  • 1
  • 3
  • 12

3 Answers3

3

PHP supports dynamically added properties to a Object,so:

class Foo{

}

$foo = new Foo();
$foo->{'AqUV-AETH'} = 'data1'; // add and init new porperty to a Object
$foo->{'AqPM2.5'} = 'data2'; 

echo $foo->{'AqUV-AETH'}; // access special porperty name with $obj->{'name'}
PHPJungle
  • 502
  • 3
  • 16
1

Actualy you can make those property's like this:

class foo {

public function __construct () {
    $this->{"AqUV-AETH"} = 1;
    $this->{"AqPM2.5"} = 600;
}}

{""} allows you to use other characters in your variable names just use the same way to call-them

Bruce
  • 1,647
  • 4
  • 20
  • 22
Marcel R
  • 11
  • 2
1

This kind of thing will never be convenient in PHP (nor in a lot of other languages, for that matter).

The simplest answer is to use an array instead of an object. Array element names are referenced as strings, so no problem.

Another option would be to use an array internally inside the class, and then have a "magic" __get() method that resolves properties to the name. When referencing the property name, you'll need to use {} braces to work around PHP syntax issues.

A pragmatic solution may be to use some kind of subsitution character(s) in the PHP code. So for example, you could use underscore in place of hyphen, so your property name would be public AqUV_AETH = null;, and then do a conversion on it when you import/export to the API.

But for my money, the best solution of all would be to have more sensibly named properties all round -- give all the properties in your code meaningful names rather than the somewhat terse codes from the API, and then have code inside your class to map the named properties to their names from the API whenever you need to do an import or export. There's no need for you to stick with their naming convention inside your code.

I hope that gives you some ideas.

Simba
  • 4,952
  • 3
  • 19
  • 29
  • 1
    this is what i was going to suggest - human friendly api; actual variable names only are needed internally when building the http request. – pete Jun 26 '15 at 11:29