published on in PHP
tags: notice php

Notice: Can I create `New` function in a class in PHP?

Why not? Let’s try ;)

<?php
class wsGallery extends wsCore {
  const _PRIVATE = 1;
  const _PUBLIC  = 2;
  const _HIDDEN  = 3;
  const _SYSTEM  = 4;
  const _PROFILE = 5;

  private function __construct($gid) {
    parent::__construct();
    $this->gallery = wsCache::galleries()->findOne(array(
      '_id' => new MongoId($gid)
    ));
    $this->full_images = wsCache::images()->find(
      array('gallery_id' => $gid)
    );
  }
  static function new($name, $type) {
    $gallery = array(
      'name'     => $name,
      '_type'    => $type,
      'owner_id' => USER_ID,
      'images'   => array(),
      'requests' => array(),
      'accepted' => array()
    );
    wsCache::galleries()->insert($gallery);

    return new self($gallery['_id']);

  }
}

wsGallery::new('My gallery', wsGallery::_PRIVATE);

If you want to do this (or similar)… Forget the new keyword:

<?php
class wsGallery extends wsCore {
  const _PRIVATE = 1;
  const _PUBLIC  = 2;
  const _HIDDEN  = 3;
  const _SYSTEM  = 4;
  const _PROFILE = 5;

  private function __construct($gid) {
    parent::__construct();
    $this->gallery = wsCache::galleries()->findOne(array(
      '_id' => new MongoId($gid)
    ));
    $this->full_images = wsCache::images()->find(
      array('gallery_id' => $gid)
    );
  }
  static function create($name, $type) {
    $gallery = array(
      'name'     => $name,
      '_type'    => $type,
      'owner_id' => USER_ID,
      'images'   => array(),
      'requests' => array(),
      'accepted' => array()
    );
    wsCache::galleries()->insert($gallery);

    return new self($gallery['_id']);
  }
}

wsGallery::create('My gallery', wsGallery::_PRIVATE);

It’s another stupidity of PHP… the new keyword is reserved for instances [new wsGallery()] But why? The parser can’t understand the Regular Expressions? new Classname() is not equal with Classname::new().

The first is:

/\bnew\b [a-zA-Z_][a-zA-Z0-9_]*/

and the second is like:

/\b[a-zA-Z_][a-zA-Z0-9_]*::[a-zA-Z_][a-zA-Z0-9_]*/

(or similar but the formats aren’t the same… Really not)