The Huawei thing

A few months ago I was asked for comment on the idea that an embattled Theresa May was about to approve Huawei for the UK’s 5G roll-out, and this was a major security risk. Politics, I assumed. No one who knew anything about the situation would worry, but politicians making mischief could use it to make a fuss.

Now it’s happened again; this time with Boris Johnson as Prime Minister. And the same old myths and half-truths have appeared. So is Chinese company Huawei risky? Yes! And so is everything else.

Huawei was founded by a brilliant entrepreneurial engineer, Ren Zhengfei in 1987, to make a better telephone exchange. It came from the back to become the market leader in 2012. It also made telephones, beating Apple by 2018. While the American tech companies of the 1980’s grew old and fat, Huawei kept up the momentum. Now, in 2020, it makes the best 5G mobile telephone equipment. If you want to build a 5G network, you go to Huawei.

Have the American tech companies taken this dynamic interloper lying down? No. But rather than reigniting their innovative zeal, they’re using marketing and politics. Fear, Uncertainty and Doubt.

Some arguments:

“Huawei is a branch of the evil Chinese State and we should have nothing to do with it.”

Huawei says it isn’t, and there’s no evidence to the contrary. The Chinese State supports Chinese companies, but that’s hardly novel. And whether the Chinese State is evil is a subjective judgement. I’m not a fan of communist regimes, but this is beside the point if you’re making an argument about technology.

“Huawei is Chinese, and we don’t like the government or what it does”.

So we should boycott American companies because we don’t like Trump? We do business with all sorts of regimes more odious that the CPC, so this is a non-argument. You could make a separate argument that we should cease trade with any country that isn’t a liberal democracy, but this could be difficult as we’re buying gas from Russia and oil from the Middle East.

Please generate and paste your ad code here. If left empty, the ad location will be highlighted on your blog pages with a reminder to enter your code. Mid-Post

“Huawei works for the Chinese secret service and will use the software in its equipment to spy on, or sabotage us.”

First off, Ren Zhengfei has made it very clear that he doesn’t. However, there have been suspicions. In order to allay them, Huawei got together with the UK authorities and set up the HCSEC in Banbury. Huawei actually gives HCSEC the source code to its products, so GCHQ can see for itself; look for backdoors and vulnerabilities. And they’ve found nothing untoward to date. Well, they’ve found some embarrassingly bad code but that’s hardly uncommon.

Giving us access to source code is almost unprecedented. No other major tech companies would hand over their intellectual property to anyone; we certainly have no idea what’s inside Cisco routers or Apple iPhones. But we do know what’s inside Huawei kit.

“Because Huawei manufactures its stuff in China, the Chinese government could insert spying stuff in it.”

Seriously? Cisco, Apple, Dell, Lenovo and almost everyone else manufacturers its kit in China. If the Chinese government could/would knobble anything it’s not just Huawei. This is a really silly argument.

Conclusion

So should we believe what the American’s say about Huawei? The NSA says a lot, but has offered no evidence whatsoever. The US doesn’t use Huawei anyway, so has no experience of it. In the UK, we do – extensively – and we have our spooks tearing the stuff apart looking for anything dodgy. If we believe our intelligence services, we should believe them when they say
Huawei is clean.

Being cynical, one might consider the possibility, however remote, that America is scared its technology companies are being bested by one Chinese competitor and will say and do anything to protect their domestic producers; even though they don’t have any for 5G. Or if you really like deep dark conspiracies, perhaps the NSA has a backdoor into American Cisco kit and wants to keep its advantage?

The US President’s animosity to trade with China is hardly a secret. Parsimony suggests the rest is fluff.

PHP for C++, C# or Java Programmers

Introduction

Scripting languages are horrible. All of them. However, it is probably true to say that PHP is better than Python, so it’s not all bad. While it shares the latter’s disregard for data types, it does have classes and a full set of statements for structured flow control. Because PHP could run from within Apache, without the overhead of CGI, it gained great popularity for web sites, where “web developers” have committed unspeakable sins against computer science; but it’s not the languages’ fault.

If you’re a C++ programmer, the paragraph above will sound reasonable. If you’re taking issue with my dislike of scripting languages for software engineering, you’re reading the wrong document, because I don’t hold back.

These notes are intended as a quick crib sheet for dealing with PHP for anyone who understands basic C++ or derived languages such as Java and C#), together with Unix scripting. PHP borrows from both. It’d be hard to call yourself a programmer if you didn’t used both, but if you’ve somehow avoided the Bourne (or BASH for penguinistas) you might want to read up on the basics of these first. Whilst the control structures are borrowed from C, the variable and string syntax will be familiar from shell.

This document cuts to the chase – a quick start to PHP for programmers. It’s not a tutorial in how to program for beginners. I come neither to bury nor praise PHP. It has its uses, as do all scripting languages, and can be great fun for a quick lash-up.

Nonsense

Let’s not sugar coat this – there are aspects of PHP that don’t make a lot of sense. Here are a few you should be aware of to avoid a load of confusion:

  • Overloading in PHP does not refer to overloading in anything like the normal sense of the word in computer languages. It’s actually used to talk about interpreter hooks. There is no function overloading in PHP.
  • Case sensitivity is inconsistent. Variable and constant names, and labels, are case sensitive. Other things are not, including function names, class names, keywords and namespaces.
  • PHP syntax isn’t necessarily backward compatible, and new syntax is added on minor versions. This document is based on PHP 7.4, but mentions some important differences with 5.x and 7.x releases.
  • The meaning of “declare” has nothing to do with declaring anything; it sets interpreter options.
  • Multiple inheritance isn’t supported as a matter of design, which is then circumvented using a weird non-class called a trait.
  • The type declaration of “const” does not refer to an immutable object (it’s a way of declaring a manifest constant, and nothing more).
  • Things like parametric polymorphism aren’t supported, but reflection is used to simulate them at run-time.

File format

PHP interprets lines from a text file:

#!/usr/local/bin/php
<!--?php
print (“Hello World\n”);
?-->

Like any other script language, it helps to put the name of the interpreter in the first line of the file although if it’s being run through Apache you won’t need to.

#!/usr/local/bin/php

If you’re using Linux rather than Unix this may be at /bin/php, of course.
Next there is the <!–?php … ?–> business. The PHP interpreter was intended to allow PHP code to be embedded in an HTML tag, so this is the opening and closing of a tag to get it to take notice of the stream.

On later (current) versions you can dispense with the HTML comments and wrap the file in <?php … ?>

And in the middle, there’s our print statement. And it is actually a statement; not a function. I just put the brackets around it because I could. It prints a single string.

Note the semicolon on the end – like ‘C’, line breaks are irrelevant and statements are ended by a ‘;’

PHP also includes the echo statement, which takes multiple arguments like echo in the shell:

echo "foo", "bar";

Having two ways of doing the same thing is all part of the fun on PHP.

Comments

As you might expect from the offspring of C++ and Bourne shell, you can use both types of comment. C++ // and /* */, as well as #. For the sake of sanity, I’ll stick with // in this document, but it’s a matter of taste which you prefer.

Constants

Literal constants follow the conventions you’re used to, with the exception of string literals, which follow normal shell convetions. That’s to say that they may be quoted with either a single (‘) or double (“) quote. A single quote does not produce an integer character code. This is covered in more detail in the Strings section.

Other literal constants are as you’d expect – 123 is a cardinal; 1.23 is a float, and True is a Boolean.

Manifest constants in PHP are, by convention, declared in UPPER CASE, although it doesn’t matter to the language. There are two ways to do it:

const PI = 3.141592;
define ("Euler", 2.71828);

If you redefine a constant PHP will ignore you, silently. In other words, the first definition persists even though this is irrational.

At first sight, define() may look like a pre-processor option, but in an interpreted language this doesn’t really make sense. However, in combination with a conditional, you can use define() to create a constant with a value determined at run-time. The const modifier is a later addition to PHP and works like a compile-time definition (but with no error-checking). It has the advantage that it’s sensitive to namespaces and you’ll probably prefer it going forward. Until PHP 5.3 it only worked in class scope, but this restriction has gone.

It’s widely believed that the initialiser in a const declaration can’t be an expression. It can (since PHP 5.6); it just has to be a constant expression – e.g. const RPI = 1/PI;

Operators

PHP implements the usual operators with the usual precedence, with a few extras.

‘.’ is the string concatenation operator.

‘**’ is the exponential operator (from PHP 5.6 onward).

!== and === differ from != and == in that they must be identical – no type conversions are performed so the expressions being compared must be of the same type to be the same value.

<> is an alternative to !=, although bizarrely it has a precedence one below.

Only a maniac would use this feature in coding.
Comparison operators also work on arrays, and plus (‘+’) can be used to concatenate arrays (i.e. a union operator).

And as of PHP 7, there’s the <=> operator. It returns zero if both arguments are the same, -1 if the left argument is less than the right, and +1 if it’s greater. This is similar to the strcmp() function in the POSIX library, but the thought process that came up with it being a good idea as an operator is baffling.

Variables and Types

All variables are prefixed with a $, whether they appear in an lvalue and as an rvalue (unlike shell). But they don’t have a type.

$a=2;
$b=$a*10;
$a='Twenty: ';
echo $a ,$b;

As you can see, I stored an integer in $a, and then stored a string in it. Variables do have dynamic typing, although at any one time they are of a specific type. There’s a function to return the current type as a string:

$myint=123;
$mystr="A string";
$myreal=3.14159;
$mybool=true;
echo gettype($myint),": ",$myint,"\n";
echo gettype($mystr),": ",$mystr,"\n";
echo gettype($myreal),": ",$myreal,"\n";
echo gettype($mybool),": ",$mybool,"\n";
Output:
integer: 123
string: A string
double: 3.14159
boolean: 1

There are several functions like is_int() for other types, and they return true or false as you’d expect. And speaking of Boolean values, true is the integer 1, whereas false is an empty string. For conditionals, 0 or non-zero work as false or true too; as do empty or non-empty strings.

$a = (3 > 5);
$b = (3 < 5);
print ("a=$a, b=$b");


Output: a=, b=1

Variables in PHP are self-creating on first use, and that includes using them as part of an rvalue. The following nonsense is legal, with $b printing as an empty string. If you’re lucky you’ll get a notice-level warning to alert you to the fact you’ve messed up, but this isn’t guaranteed by any means.

$a="Hello";
echo $a, $b;


Output: Hello

Strings

Numeric expressions work as you’d expect. Strings can be concatenated using the ‘.’ operator (which you should separate with a space. Expression types are cast in a sensible way, so “Testing” . 123; results in a string containing “Testing123”.

$name='Mary';
$day='Monday';
$age=6;
print ("It will be $name's Birthday next $day and she will be $age.\n");

Output: It will be Mary's Birthday next Monday and she will be 6.

As you can see I haven’t quoted the single quote – there’s no need. The usual conventions apply, so to get a double quote you’d need \”. If your variable name isn’t obvious because it has printable characters immediately before or after, put it in curly brackets thus:

{$name}

PHP has dozens of string functions for you to look up, including everyone’s favourite strlen(). Some take the form str_xxx() and some are named strxxx(), for no good reason I can see except for PHP being bonkers.

Arrays

PHP doesn’t go for types, so arrays are also un-typed; and can be of mixed type values. Arrays are also dynamic. In fact they’re really lists, but PHP heads called them arrays anyway.
You can create arrays with an array() function, but the simple way is self-explanatory assuming you’re using a relatively recent version of PHP, as below:

$a1 = []; // Empty array
$a2 = [1,2,3,"Tom","Dick","Harry"]; // Initialised with stuff

If you’re using ancient PHP you could get the equivalent using:

$a1=array();
$a2=array(1,2,3,"Tom","Dick","Harry");

In the above, $a2[3] would be “Tom”, as you might expect. However, PHP arrays only default to zero based integer addressing. The index can be anything else, like a string. (Associative array is a name that may sprint to mind). The full syntax for initialisation is:

 $a3 = [ "red" => "rouge", 
"blue" => "bleu",
"green" => "vert",
"yellow" => "jaune" ];


And $a3[“green”] would return “vert”. You can mix integer indexes in with the strings, and if you don’t specify an index for an element it defaults to the next integer index. That’s to say, the last integer index used plus one. For example the following is perfectly legal, even if it isn’t sane:

$a3 = [ "red" => "rouge",
6 => "bleu",
"green" => "vert",
"jaune" ];


print ("a3[7] = $a3[7] \n");



Output: a3[7] = jaune

Note that this wouldn’t be $a3[8] or $a3[3]; both of which you might expect. This is because the second element had its index set to 6, the third element was given a key and the eight element defaulted to the next integer – 6+1 = 7. $a3[0] won’t get your “rouge”, as it’s got a key instead.

If you’re using an associative array (or integer indexed one), the risk is that PHP will bomb out if it can’t find the index/key. You can avoid this using the array_key_exists() function. It returns a bool and takes two arguments, the first being the key and the second the array. There are a number of array functions similar to those in the STL – in_array(), array_push(), array_pop(), count() sort(), and so on.

To add elements to an array this syntax is:

$a2[] = "Another";
$a3["purple"] = "violet";

The first adds an item indexed by the next available integer index. The second form adds a key/value pair. And yes, if the key or index already exists you’ll over-write the current value with your new one.
To remove an item from an array, you need the unset() function. It basically takes one or more variables or array locations as parameters and removes them, as if they’ve never been set

unset ($a3[6], $a3["green"); // Blue and green should never be seen.

Multi-dimensional array access is the same as for ‘C’ – i.e. as many indexes as you need each in their own square brackets

Flow Control

I hope you had fun with variables and strings. Now we come to some good news. The flow control structures in PHP are the same as ‘C’, Java and C#. Including blocking statements together with curly brackets.

All of the following are valid and work exactly as you’d expect.

if (conditional) statement;

if (conditional) { statement; statement; … }

do statement; while (conditional);

do statement; while (conditional);

while (conditional) statement;

for (initialiser; conditional; increment) statement;

switch (value) // Value can be any type
{
case 1:
statement;
break;
case 2:
statement;

default:
statement;
}

goto label;

There’s also an “enhanced” for loop as in Java, C# or shell script, or the C++ STL:

foreach (array as item) statement;

Basically, each time through the loop the variable “item” is replaced with the next element in “array”.

foreach ($a3 as $element)
print ("The item is $element\n");

Whilst Java omits goto; PHP doesn’t, in common with C, C++ and C#.

In complex code a goto statement can simplify flow control considerably, although it’s hard to come up with a trivial example where it makes sense. Here follows a trivial example where it doesn’t make sense, but you get the idea. Note the label ends in a colon (“:”).

goto mylabel;
print ("This will NOT be printed\n");
mylabel:
print ("Output will start here\n");

Finally, “break” and “continue” work as expected in loops.

In spite of having a full set of structured statements, many PHP developers seem to like using exceptions to implement program flow. More on this later.

Functions/Methods

PHP functions are a simplified version on C/C++/Java/C# syntax. Note that functions are called methods in Java.

So here’s a function:

function square ( $x )
{
return $x * $x;
}

print("2 squared is ".square(2)."\n");

Output: 2 squared is 4

And that’s about it. The keyword “function” tells the interpreter it’s about to get a function definition.

As PHP isn’t typed, there’s no need to worry about specifying a return type, or parameter types. This is probably one of the worst aspects of K&R ‘C’, which was corrected with function prototypes in the ANSI specification. PHP made the same initial mistake, and implemented something similar to function prototypes in PHP version 5 onwards where they were known as type hints. From version 7 they’re called type declarations and have been extended.

Even with type hints, function name overloading isn’t possible; there is no compile-time polymorphism as there is no compilation. However, introspection and reflection are supported in PHP and this is used for un-checked dynamic polymorphic constructs.

The syntax for declaring an (optional) function return type is different to other languages (PHP 7 onward):

function sum($x, $y): float
{
return $x + $y;
}
print("The type of sum() = ".gettype(sum(2,3))."\n");

Output: The type of sum() = double

As you can see, PHP also “rounds up” floats to doubles. The value of return types may be a bit limited, as most of the time dynamic typing will silently convert it to whatever seems right anyway.

In addition to class names, the return type of a function can be one of self (instance of the class the method was defined on), array or callable. From PHP 7 onward you can have book, float, int and string. In 7.2 return types of iterable and object have been added.

The syntax for arguments is the same as C/C++/Java/C#. If you want to use argument type checking, you can write it as:


function square ( int $x )

It’s worth noting that without the optional type checking (which is normal for PHP), a function will return something random if you give it unexpected arguments. There’s a convention that a NULL will be returned in such circumstances, but it’s only a convention.

You can pass by reference by prefixing the variable name with an ampersand “&”, (C++ style).

function square ( &$x )
{
$x = $x*$x;
}

If a function returns a reference, prefix its name with &.

function &add_tax (&$x)
{
$x *= 1.2;
return $x;
}

You can also have default parameter in the same way as C++

function printwhen ( $product, $when="sometime")
{
print ("Your $product will be ready $when.\n");
}

A variable arguments list is accomplished using … as prefix to a variable, which effectively becomes an array of the passed values.

function total (...$numbers)
{
$tot = 0;
foreach ($numbers as $num)
$tot+=$num;
print "The total is $tot\n";
}


total (3,1,4,1,5);
Output: The total is 14

And for one final piece of craziness you can call a function by having its name stored in a string.

function hi()
{
print "Hello\n";
}
$greeting ="hi";
$greeting();

This does not make it a first-class function, or even a pointer to a function. It’s a recipe for disaster.

If you’re wondering about void functions, there’s no such thing, but if you don’t hit a return statement PHP will return a NULL.

Lambda (closure; anonymous) functions are supported:

function myfunction ($a1, $f1)
{
print ("a1=$a1\n");
$f1 (456);
}
myfunction (123, function ($a) { print ("a=$a\n"); } );

This will output

a1=123
a=456

You can make the lambda inherit variables from the local scope with use():

$x = 1; $y = 2;
myfunction (123, function ($a) use ($x, $y) { print ("a=$a, x=$x, y=$y\n"); } );

Output:

a1=123
a=456, x=1, y=2

Just keep reading it until in makes sense.

Classes

The class/object model is pretty much a subset of the same as C++, which has been borrowed by Java and C#. If you’re not used to C++ terminology:

  • method = member function
  • property = member variable = attribute

You define a class using the class keyword followed by the name. The modifiers const, static, public, private and protected have the usual meaning. By default everything is private, but this can be overridden on an element-by-element basis. Unlike C++, you can’t use public:, protected: or private: as labels to change subsequent declarations. There’s no such thing as a “struct” in PHP (which is a class where members default to public, if you’re coming from Java or C#), or a union.

The final keyword can be applied to a class or method, and prevents the class being used as a base for a derived class, or the method being overridden. It’s not the same as Java when it comes to class constants; in PHP use the keyword “const” instead.

A constructor is defined as “public function __construct() …”, with optional arguments. Remember, function name overloading isn’t supported. A class’ destructor is a function named __destruct().

Functions starting with __ (two underscores) are “magic” in PHP. Additional magic functions defined include __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debugInfo(), and might best be described as hooks within a class that get called by the interpreter in particular circumstances. See a PHP reference for further details.

The pseudo-variable $this has the same meaning as other languages. There’s also a keyword “self” (no $) that can be used to refer to the class rather than this particular instantiation (object of class), and “parent”, to refer to the parent class where inheritance is used.

To reference an element within an object of a class, use the arrow operator (“->”), as if it’s a structure pointer dereference in C++. In languages without pointers, like Java and C#, you always use the “.” operator to specify an element, whatever the underlying reality. In ‘C’, the choice of . and -> makes a difference. In PHP, you always use “->”; at least you don’t have to think about it.

So here’s an example, which should be self-explanatory, but I’ll explain it afterwards anyway:

class myClass
{
public $myVar = "My default value";

function printme()
{
print("myVar = " . $this->myVar . "\n");
}
function printhello()
{
print("Hello!\n");
}
}

$myObject = new myClass;
$myObject->printme();

$myObject->myVar = "New value";
$myObject->printme();
myClass::printhello();

Output:

myVar = My default value
myVar = New value
Hello!

First off, note that the attribute $myVar is declared with at $ but this isn’t used when it’s referenced as an element. I’ve made it public so it can be referenced from outside the class.

I haven’t made the printme() method public; it is by default! Inside it I’ve used $this->myVar to get at the attribute. Without the $this-> it won’t be in scope. In other words, properties are NOT in scope of methods.

PHP supports the scope resolution operator “::”, which is used above for the sake of simple demonstration. printhello() is the same as a Class method in Java. Note that myClass::printme(); would fail, because no instantiated object exists for $this to refer to.

The scope resolution becomes important when you use derived classes.

class myChild extends myClass
{
public $childVar = "I'm only a kid";

function printme()
{
myClass::printme();
print("myVar another way = " . $this->myVar . "\n");
print("childVar = " . $this->childVar . "\n");
}
}

$myChildObject = new myChild;
$myChildObject->myVar = "I'm the parent object.";
$myChildObject->printme();

What won’t work is if you have properties of the same name in both the base and derived class. With the auto-creating variables in PHP, “declaring” another myVar in myChild will make it indistinguishable from the same property in myClass. No warning. Just confusion; so take care you never do it. If BOTH properties are private, that’s fine.


class myClass
{
private $myVar = "I'm the parent";
function printme()
{
print("myVar in base = " . $this->myVar . "\n");
}
}

class myChild extends myClass
{
private $myVar = "I'm only a kid";
function printme()
{
myClass::printme();
print("myVar in child = " . $this->myVar . "\n");
}
}

$myObject = new myChild;
$myObject->printme();

Output:

myVar in base = I'm the parent
myVar in child = I'm only a kid

To access a static class property or function (aka attribute or method) prefix it with the class name and the scope resolution operator (not a dot!)
Interface and Abstract Classes

In C++ an interface class contains one or more pure virtual functions (abstract methods) and nothing else. It’s a special case of an abstract class. However, because a class is a class, it’s treated as any other. Multiple inherence lets a new class inherit as from as many parents as it likes; interface or not.

In Java and C#, with single inheritance, multiple interface classes can also be inherited. However, they’re up-front about an interface class, with its own special keyword. PHP shares this, as well as Java’s “implements” keyword when specifying an interface in a class declaration.

Here’s a simple example of an abstract class:

abstract class AbstractClass
{
// Force an extending class to define this method
abstract protected function printme();

// Example method everything will inherent

public function printHello ()
{
print "Hello World\n";
}
}

class ConcreteClass extends AbstractClass
{
public function printme()
{
parent::printHello();
print("I’m concrete\n");
}
}

$rubble = new ConcreteClass;
$rubble->printme();


Output:

Hello World
I’m concrete

If you’re having an interface class (abstract class consisting of only pure virtual functions), in PHP you say so. A concrete class can inherit multiple interfaces (using a comma separated list), even if it can only extend one base class.

interface iPrintable
{
public function printme();
}

interface iFriendly
{
public function printHello();
}

class MyClass implements iPrintable, iFriendly
{
public function printme()
{
print("I’m concrete\n");
}

public function printHello()
{
print("Hi there!\n");
}
}

$myObject = new MyClass;
$myObject->printHello();
$myObject->printme();

Output:

Hi there!
I’m concrete

I’ve previously mentioned that PHP doesn’t support multiple inheritance. To get around this PHP does include something called a trait (from PHP 5.4). If the answer to your problem involves using traits, you’re probably doing something wrong., but you’ll need to be aware of them.

class MyClass
{
public function printHello()
{
print ("Hello");
}
}

trait PrintWorld
{
public function printWorld()
{
print ( " World!\n");
}
}

class Greeting extends MyClass
{
use PrintWorld;
}

$myObject = new Greeting();
$myObject->printHello();
$myObject->printWorld();


Output: Hello World!

As you can see in the code, MyClass and Greeting are both classes. Greeting extends MyClass but uses a trait called PrintWorld. As a result, Greeting inherits the printHello() method from MyClass and the printWorld() method from the PrintWorld trait. You can use as many traits as you like, but there are, unsurprisingly, more limited than a full class. If they have a use, it’s to lump a load of functions together in a convenient place. If you use traits for anything tricky, and need to resolve clashes and work out precedence, you’ll have to read the full manual; and when you do remember it was your fault for getting into the mess in the first place, because I warned you.

Namespace

PHP does support namespaces from PHP 5.3 onward, but it’s clunky. The keyword “namespace” followed by your chosen name must be the first thing in the source file, other than the opening tag (<?php). This is very strict, meaning that you can’t have anything before the tag, including initial html.

Good:

 <?php
namespace Example;

Fatal Error:

 <?php
namespace Example;

Namespaces are hierarchical, and the path can be separated using a backslash (‘\’) – not the scope resolution operator. You can access anything public in a different namespace if you know how to get to it:

namespace test/junk/foo;
\test\junk\somefunction();

You can import classes from another namespace with the “use [… as …]” keyword:

 use \test\junk\myClass as hisClass;

From PHP 5.6 you can also have “use const …” and “use function …”

Reflection and Introspection

Because PHP is interpreted it’s technically possible to mess around with objects at runtime; not the object’s members but the languages’s notion of an object. This can lead you many interesting and amusing problems, but is sometimes the least-worst option for dealing with the fluid object typing inherent in the language.

Let’s be clear here – in assembly language its possible to use self-modifying code. It was clever, and when you had 1K of core to play with, its use was justified. It’s also possible in ‘C’ – you can find the address of a function easily enough and modify the op-codes. However, it’s pretty obvious to anyone that this is a path to madness. And with modern compiler optimisation, wholly unnecessary.

So where you see introspection used sensibly is on checking the arguments to a function. To PHP, every object can look like any other, which appears to be a good reason why parametric polymorphism can’t happen. However, if you write a single function that examines the objects actually passed and acts accordingly.

If you want to read more about this, as ever, the PHP documentation is the place yo go. However, here’s a quick example to give you the idea of how to get started.

class Foo
{
private $my_private_var;
public $my_public_var;
protected $my_protected_var;
function print_my_name ()
{
echo "My name is Foo\n";
$this->my_private_var = "I'm Private";
$this->my_public_var = "I'm Public";
$this->my_protected_var = "I'm Protected";
}
}

// Instantiate a Foo, check it's working and set it's variables.
$test = new Foo;
$test->print_my_name();

// These two functions get the type of a variable
// (in this case it'll be an object) and the class
// name of the object, so your function can decide what
// to do with it.
echo "gettype() returns " . gettype($test) . "\n";
echo "get_class() returns " . get_class($test) . "\n";

// As these next functions are returning arrays, we're going to
// use the print_r() function to print them in readable format
// from now on. And here's where it starts to get silly.

echo "Output of get_object_vars()\n";
print_r(get_object_vars ($test));

echo "\nOutput of get_class_vars()\n";
print_r(get_class_vars ('Foo'));

echo "\nOutput of get_class_methods()\n";
print_r(get_class_methods ('Foo'));

echo "\nOutput after casting object to array\n";
print_r((array)$test);

echo "\nvar_dump() after casting to an array\n";
var_dump((array)$test);

// And now for something really horrible:

$a=(array)$test;
$a["Var_no_one_knows_about"] = "I've got a bad feeling about this.";
$test=$a;

echo "\nThe Foo object after we've hacked it.\n";
print_r((array)$test);

Output

 My name is Foo
gettype() returns object
get_class() returns Foo
Output of get_object_vars()
Array
(
[my_public_var] => I'm Public
)
Output of get_class_vars()
Array
(
[my_public_var] =>
)
Output of get_class_methods()
Array
(
[0] => print_my_name
)
Output after casting object to array
Array
(
[Foomy_private_var] => I'm Private
[my_public_var] => I'm Public
[*my_protected_var] => I'm Protected
)
var_dump() after casting to an array
array(3) {
["Foomy_private_var"]=> string(11) "I'm Private"
["my_public_var"]=> string(10) "I'm Public"
["*my_protected_var"]=> string(13) "I'm Protected"
}
The Foo object after we've hacked it.
Array
(
[Foomy_private_var] => I'm Private
[my_public_var] => I'm Public
[*my_protected_var] => I'm Protected
[Var_no_one_knows_about] => I've got a bad feeling about this.
)

Debugging

There are many PHP functions intended for debugging, but here are a few tips to start you off.

print_r() – Pretty print a variable or array.

var_dump() – As above, but with more information (particularly its type)

debug_zval_dump() – As above, but with reference counts for debugging the PHP interpreter.

Here’s a quick example.

$a = ["One","Two","Three"];
print_r($a);
var_dump($a);

Output

 Array
(
[0] => One
[1] => Two
[2] => Three
)
array(3) {
[0]=> string(3) "One"
[1]=> string(3) "Two"
[2]=> string(5) "Three"
}

One very useful feature of the var_dump() function is that when it’s used for a class it can be overridden by the special “__debugInfo()” member function, which can output the contents in any way you see fit. The default is to dump the lot.

Because debugging is something you’re likely to want to do without wanting to read the whole PHP manual, I’ll go into a bit more detail. These functions will write to the standard output (or HTML stream if you’re using it for a web site). To catch teh output and write it to a file use something like this:

// First we capture the output into an output buffer
// and store the result in the string.
ob_start();
var_dump($a);
$stuff = ob_get_clean();

// Then we append it to a text file of our choice
$fp = fopen("/var/log/mylog.log", "a");
fwrite($fp, $stuff);
fclose($fp);

It’s easier to capture print_r() as it has a default final parameter; a flag to return the output as a string rather than printing it. In this example I’m using the special variable $GLOBALS to dump every global variable.

$stuff = print_r($GLOBALS,true);

Miscellanies

Running shell commands

PHP supports the back-tick operator in the same way as the Bourne shell. Anything between two back-ticks (‘`’) will be passed to the shell, and stdout will replace the whole lot in the interpreted line.

declare()

There’s a keyword “declare” that is akin to a compiler #pragma. It sets various options for the interpreter from this point onward; or for the following block. It doesn’t actually declare anything.

Examples:

 declare (strict_types=1);

This will actually enable type checking on function arguments, assuming someone’s bothered to define types in the first place.

 declare(encoding='ISO-8859-1')
{

}

The code between the { … } is encoded using ‘ISO-8859-1’ (i.e. 8-bit extended ASCII, not Unicode).

include/require

These statements simply include an external file into the interpreter stream at this point.

 include “something.php”;

Require is similar, except it’ll halt execution with a fatal error if the file isn’t found. There are special versions, include_once and require_once, which will refrain from including the named file if it’s been included before.

@ Error control operator

Being an interpreted language, you won’t be bothered by any compile-time errors drawing attention to mistakes in your code. If you want to prevent pesky run-time errors to, you can prefix any expression you like with a commercial at (‘@’), and it’ll suppress any errors or warnings that would otherwise highlight your mistakes. This includes fatal errors, so your script will just stop dead, causing the user to utter many interesting terms of endearment about you when they find out.

As far as I can make out, the @ operator technically sets the run-time error reporting level to zero (that which is returned by error_reporting ()). Any error handlers you’ve set will still be called.

Auto loading functions

TBC

Iteration

TBC

Exception Handling

There really needs to be a section on exception handling. It’s very similar to the Java model, but the way it’s used makes me nauseous and I can’t bring myself to write about it right now.

Jails on FreeBSD are easy without ezjail

I’ve never got the point of ezjail for creating jailed environments (like Solaris Zones) on FreeBSD. It’s easier to do most things manually, and especially since the definitions were removed from rc.conf to their own file, jail.conf. (My biggest problem is remembering whether it’s called “jail” or “jails”!)

jail.conf allows macros, has various macros predefined, and you can set defaults outside of a particular jail definition. If you’re using it as a split-out from rc.conf, you’re missing out.

Here’s an example:

# Set sensible defaults for all jails
path /jail/$name;
exec.start = "/bin/sh /etc/rc";
exec.stop = "/bin/sh /etc/rc.shutdown";
exec.clean;
mount.devfs;
mount.procfs;
host.hostname $name.my.domain.uk;
# Define our jails
tom { ip4.addr = 192.168.0.2 ; }
dick { ip4.addr = 192.168.0.3 ; }
harry { ip4.addr = 192.168.0.4 ; }
mary { ip4.addr = 192.168.0.5 ; }
alice { ip4.addr = 192.168.0.6 ; }
nagios { ip4.addr = 192.168.0.7 ; allow.raw_sockets = 1 ; }
jane { ip4.addr = 192.168.0.8 ; }
test { ip4.addr = 192.168.0.9 ; }
foo { ip4.addr = 192.168.0.10 ; }
bar { ip4.addr = 192.168.0.11 ; }

So what I’ve done here is set sensible default values. Actually, these are probably mostly set what you want anyway, but as I’m only doing it once, re-defining them explicitly is good documentation.

Next I define the jails I want, over-riding any defaults that are unique to the jail. Now here’s one twist – the $name macro inside the {} is the name of the jail being defined. Thus, inside the definition of the jail I’ve called tom, it defines hostname=tom.my.domain.uk. I use this expansion to define the path to the jail too.

If you want to take it further, if you have your name in DNS (which I usually do) you can set ip.addr= using the generated hostname, leaving each individual jail definition as { ;} !

I’ve set the ipv4 address explicitly, as I use a local vlan for jails, mapping ports as required from external IP addresses if an when required.

Note the definition for the nagios jail; it has the extra allow.raw_sockets = 1 setting. Only nagios needs it.

ZFS and FreeBSD Jails.

The other good wheeze that’s become available since the rise of jails is ZFS. Datasets are the best way to do jails.

First off, create your dataset z/jail. (I use z from my default zpool – why use anything longer, as you’ll be typing it a lot?)

Next create your “master” jail dataset: zfs create z/jail/master

Now set it up as a vanilla jail, as per the handbook (make install into it). Then leave it alone (other than creating a snapshot called “fresh” or similar).

When you want a new jail for something, use the following:

zfs clone z/jail/master@fresh z/jail/alice

And you have a new jail, instantly, called alice – just add an entry as above in jail.conf, and edit rc.conf to configure its networ. And what’s even better, alice doesn’t take up any extra space! Not until you start making changes, anyway.

The biggest change you’re likely to make to alice is building ports. So create another dataset for that: z/jail/alice/usr/ports. Then download the ports tree, build and install your stuff, and when you’re done, zfs destroy
z/jail/alice/usr/ports. The only space your jail takes up are the changes from the base system used by your application. Obviously, if you use python in almost every jail, create a master version with python and clone that for maximum benefit.

Amazon Echo vulnerable in Smart Speaker battle

When Google launched its smart speaker it was playing catch-up with Amazon. The Echo had an established ecosystem, and unless Amazon blew it, this lead looked unassailable. The field was Amazon’s to lose.

Since then, Amazon’s arrogance seems to have taken it towards such a losing strategy. Glitzy launches of new gadgets are not enough to maintain a lead. I have a sample of pretty much every Echo device ever sold, and the newer ones aren’t that much better than the old ones. The build quality was always good, and they work.

What could damage the Echo is the slide in functionality.

Most people assumed that the rough edges – things you should be able to do but couldn’t – would be addressed in time. Google stole a march by recognising the person speaking, but Amazon has caught up. Sort-of. Meanwhile Google has been catching up with Amazon on other functionality and ecosystem.

What Amazon is failing to realise is that they’re selling smart speakers. This is the core functionality. They came up with the technology to link speakers in groups, so you could ask for something to be played “Upstairs”.

This is still there, but it’s been made almost useless. In the beginning you could play anything you wanted on an Echo. All music purchased direct from Amazon was added to your on-line library. There was also Amazon’s Prime music service. The latter has gone down hill recently, with the good stuff moved to a separate “full” streamin service. The ability to play your own music by uploading your MP3 files to your library. This facility has just “gone”, as of the start of the year.

Loyal Amazon customer assumed that it would go the other way, and that you’d be able to stream from your local source to your smart speaker groups. Amazon has blocked this, although some third party skills can play media to a single Amazon speaker. Not so smart.

Now Echo users are about to be hit again. From next month feed of BBC Radio, and other things, is changing. You’ll still be able to get them, but only on a BBC skill. The effect of this is that you can’t use an Echo as a radio alarm clock and more, the alarms will be confined to built in sounds. No longer will I be able to wake up to Radio 4’s Today program at 6am. Unfortunately I will still have to wake up at that time.

Echo Dot with Time Display – but now no use as a radio alarm

Ironically, one of Amazon’s enhancements is an Echo Dot with a time display. Just in time for it to be made useless by the software.

Looking at the change, I also strongly suspect you won’t be able to play a radio station on a group of speakers either. The speaker group technology is limited to Amazon’s own streaming service.

The Echo/Alexa system used to just work. Unless Amazon reverses these catastrophic decisions, it just doesn’t work. And now the public has a taste for this functionally, someone else can walk in and provide it.

The Religion behind Climate Change

Global Warming is real. The high priests of the peoples’ religion have proved it to the satisfaction of all true believers. Or do I mean science has proved it to all right-thinking people?

Famously, Donald Trump thinks it’s all a conspiracy. He also thought (thinks?) that Obama was a foreign import jihadist and the American Democratic Party is run by commuinists. So if Donald Trump thinks Climate Change is a trick, logic dictates that it must therefore be real, right?

I think it’s time we looked at some facts:

The world’s climate has been getting warmer. For a long time. Between the 15th and 18th Century the River Thames froze over in London. In the early 1800’s it stopped, and hasn’t done so since. Therefore things must be getting warmer. Of this there is no doubt.

Is our industrial activity the reason? Well no. We didn’t start to industrialise and burn fossil fuels until well in to the 19th Century.

So it’s pretty clear that the planet has been warming up for a long time prior to major human industrial activity. We couldn’t have started it, because it began before we burnt fossil fuels to any scale.

But… is burning fossil fuels accelerating this natural change in our climate? Well that’s another question. 97% of Climate Change scientists say it is, so it must be true. I mean: who’s going to argue with one scientist, never mind the vast majority? Scientists are honourable people, not interested in worldly matters, and have no reason to lie to us about stuff we don’t understand.

Yeah, right!

Scientists are no more or less honourable than anyone else; they do care about money and there are all sorts of reasons not to believe them. This is strikingly similar to the high priests of the old religions, don’t you think? And when you look at it, the same driving forces appear to be shaping their behaviour.

For a long time the sun went around the earth. The priests said so. Anyone with deviant views was shouted down as an idiot, and if they persisted they could eventually be burnt at the stake as an example to others. No one who argues with priests or scientists is going to be taken seriously. OR ELSE!

Did the priests have any proof that their view of the cosmos was correct? They had irrefutable evidence. Ask any priest and they’d tell you – everyone knew it was true so it must be. Who was going to appear foolish (or be put to death) by disagreeing with the consensus? But in reality the priest had other reasons to believe they were correct: their careers and livelihood depended on them sticking to the story. If you were a priest you had a good job for life. People would respect you, give you money, a nice house and plenty of food, and not expect you to get involved in nasty worldly stuff. Becoming a priest has always been a good career choice. The only career-limiting thing you could do would be to question the “truth”. If anyone did, other people would too, and eventually the religion would lose control. And if a priest did it, even more so. Errant priests would never do.

Is the modern-day scientist really any different? It’s always a good idea to follow the money. They have a job in research and their salary is paid for by someone. To get on in the world they need to publish papers, so they can’t remain silent. When they’re working for a university department set up to study climate change, its not politic to say that the subject is over-blown and the world would be better off studying something else. They’re going to say it’s important, and probably real (but that funding is needed for further research). So the the majority of scientists who are paid to believe in climate change that express an opinion are unlikely to express one that’s going to see them out of a job; and then torn apart by their colleagues for breaking the faith.

Ask a scientist not involved in climate change research whether global warming is caused by human activity, and they won’t have a strong opinion because it’s not their field. Or they’ll close ranks with the rest of the priesthood. Sorry, I meant to say “scientific community”.

Likewise, I don’t know if human activity is accelerating climate change. I suspect it may well be, but I can’t discount the fact that most academic researchers of the subject say their pay-cheque is justified. Always follow the money.

Then there are the environmentalists, myself included. I don’t bang on about human-caused climate change. I don’t know how much we are to blame. But I do know that using irreplaceable resources as thought the supply is infinite is a stupid idea. I do know that polluting the environment and destroying the natural world is a bad thing. So when a government, with the backing of its high priests of science, says it wants to reduce pollution and fossil fuel consumption I’m hardly likely to disagree, whatever the government’s real motive. (I suspect the real motive is tax revenue).

So what is it with society and its deference to scientists? In the past, if you were ill, you went to the priest for help. Not just the church infirmary; you did whatever the priest told you to in order to be cured. At the very least, you had nothing much to lose by trying. In the modern world Now we go and see a medical scientist (doctor), as we believe their results are better than the priests. Doctors can’t cure everything, in fact you could argue they can cure comparatively little. Many ailments cure themselves and the priest or doctor gets the credit anyway. But doctors do have demonstrably better outcomes than the priests they’ve displaced. If you’re ill, anyone you believe can cure you is going to be your best friend.

And then there are the politicians. Since he beginning of time the priests have been used by rulers to persuade the populous to go along with some policy or other. Do you want to plunder the tribe up the valley? Get your holy man to call it a religious duty and the plebs will do anything foolish you ask of them. Even if they’re not scared of you, they are of the priest. More precisely, they’re scared of the power that only the priest understands and can control. So the tribal chief is happy. The priest is happy because the chief keeps him in the easy life, and the plebs are happy because they’re doing the right thing for them and their mates without having to think for themselves. Or they’re dead on the battlefield.

Now, if you’re a politician and announce you want to hike taxes it unlikely to have a positive effect on your chances of re-election. Unless you can persuade the people it’s a really good idea for some reason or other. The problem is that they won’t listen to you, because you’re a politician. If you can get the high priest (or scientists) to tell them that raising taxes is virtuous, and the wrath of something will descend on them otherwise, then you can still raise the taxes you need and avoid the blame when people have less money in their pockets and you have more to spend.

I’m not saying that using taxation to reduce pollution, or finite resource consumption, is a bad thing. Anything that does that is good. But I can’t help having a nagging feeling that the motivations of governments have more to do with the revenue, as government policies usually contradict these supposed ideals unless they can make money out of it.

The switch to sustainable transport is a good example – jobs and taxes are created by cars, so building more roads is a good thing as far as they’re concerned. And they can even boost economic activity by changing the rules to encourage people to buy newly produced cars. This is contrary with the idea that they want to reduce consumption, emissions and pollution. When Trump says he wants to put industry before environment he’s just being honest.

My first draft of this diatribe ended about here, but in the summer the president of the Royal Statistical Society gave a very interesting address at their annual jamboree, which deserves a much wider audience as it drew together threads concerning why people are becoming disenchanted by experts, especially where statistics are concerned.

NSPCC claims that 6% of teenage boys read Pornhub

Petee Wanless, CEO of the NSPCC, has made a fool of himself and the organisation he represents by call8ng for unworkable restrictions to be placed o. Porn websites to prevent access by min
ors. This is on the back of some dubious looking research from avstat, who have made simar headline grabbing claims that 6% of males aged 12-16 have been looking at a site called Pornhub during the course of one month. This is based on a survey of traffic, apparently.

It’s pretty obvious to anyone in a position to see net traffic that this is most improbable, and it’s only a matter of time before the research is ripped to shreds. That the NSPCC is taking it seriously raises more questions of the organisation’s competence. Time for a new CEO, methinks.

Faith in Free Schools – Department of Education still hasn’t done its homework

The Department of Education has just lost in its bid to keep secret the “faith affiliation” of applicants planning to up Free Schools, and has been forced publish the figures by the Information Commissioner.It’s taken two years to get this information, and it’s interesting reading if you read them carefully.

Figures are not available for the first wave of 373 applications, but is (to an extent) for the second and third waves. I’ve been doing some number crunching.

Religion Wave 2 Wave 3 Total %
None 202 183 385 74.47%
Christian 45 21 66 12.77%
Muslim 17 18 35 6.77%
Plymouth Brethren 11 3 14 2.71%
Jewish 3 5 8 1.55%
Sikh 2 5 7 1.35%
Hindu 1 1 2 0.39%

The breakdown is a little strange. In Wave 3 the different Christian denominations are specified in some cases but left as “Christian” for others, as they all are on Wave 2. Except the Plymouth Brethren, who appear always to be separate from “Christian” for some reason in both sets of data. “Muslim” and “Islam” are also two different religions, apparently. Did the compiler of these statistics know anything about religions?

I also have my doubts about whether religion has been reported at all. We’re asked to believe schools like Noah’s Kingdom (Reading) isn’t religious. To quote from their ethos description: If life is based on human values then it is incomplete, but if we base our lives on the plan of God then we have a secure path.

It’s not just the Christians – how about  the Khalsa Science Academy in Leeds? Sounds Sikh to me! A quick look at their web site confirms my suspicions.

What about the Maharishi Free Schools? Non-faith? Yogi’s might fly! There’s even “Destiny Christian School” in Bedford that’s listed as secular. The clue should be in the name. It’s actually being proposed by “Miracle Church of God in Christ”, and part of the Christian Schools’ Trust who’s attitude to creationism is that it is science and they intend to teach it as such.

In short, a quick scan through the names on the list is enough to show any reasonable person that the published data is full of errors. Journalists like those at the BBC may have  taken them at face value, but they’re an insult to any thinking person.

Whatever you feel about so-called “Faith Schools”, having the data kept from us by Michael Gove and the Department of Education isn’t going help with an informed debate.

Wave 1+2 Freedom of Information data from DofE

Wave 3 Freedom of Information data from DofE

 

Interesting things at IP Expo 2012

IP Expo (nee. Storage) is on in London’s Earls Court Two for one more day. As a show it’s target remains a bit undefined (a show about Internet Protocol? Or do they mean Intellectual Property),  but that’s what can make it interesting.

This year there’s less of the mind-boggling high-end storage and more general network services from software and hardware vendors – in particular, vitallisation is the hot topic (yawn).

This is a quick impression; get down there and see for yourself or wait for a full report later.

One interesting stand is Firebrick, present for the first time. You can’t miss them, (a) because they’re in front of the main entrance one row back; and (b) they’ve got a life-sized fibreglass Orc on the stand. They’ll happily take your photograph standing with it, print it out and also give you a link to it for download within a matter of seconds.

Firebrick is a range of rather good network gateway devices (call them firewalls if you will, but that doesn’t really cover it). It’s their own technology, and it’s very clever. The latest clever stuff is the on-board SIP VoIP management, and a very reasonably priced service that can turn your 3G handset into a SIP extension. I’m not talking about a SIP App for a smartphone here; this is a SIM that integrates a mobile ‘phone in to your IP PABX.

Virtualisation is very popular, and so is security. Everyone’s got a security solution for virtualised server environments. A lot more on this topic later.

Trend has an amusing sign on their stand “Vurtualisation is becoming a reality”. Well what do you know? Are they recycling stands from five years ago, or just a bit slow to catch on. Actually, Trend has been ahead on integrating with VMWare at the hypervisor level, so it’s either a daft statement from the marketing department or an old sign but it’s too good a conversation opener to ignore. They’ll be sick if it by the end of the show.

Bit9, the security company from Massachusetts, is a the show. I like them; they’re sensible about what technology can and can’t do. This may not be a popular business model, but they give me more confidence than most of getting an accurate assessment where it matters.

Off to mingle..

BA e-ticket malware spam

Starting yesterday evening I’ve been seeing hundreds of emails sent to normally spam-free addresses claiming to be British Airways e-tickets. They are, of course, some new malware. It’s coming for a network of freshly compromised servers around the world (with a slight preference for Italy), so spam detection software won’t pick it up, and it’s new malware so virus scanners won’t find it either. As usual it’s a ZIP file containing an EXE, written in Borland Delphi I think.

The spambot code itself appears to be compiled on whatever Linux target the script attack has succeeded on, masquerading as “crond”.