I have this class:
<?php
class Test {
private $_ID;
private $_NAME;
private $_AGE;
public function setID() { $this->_ID++; }
public function getID() { return $this->_ID; }
public function setNAME($element) { $this->_NAME = $element; }
public function getNAME() { return $this->_NAME; }
public function setAGE($element) { $this->_AGE = $element; }
public function getAGE() { return $this->_AGE; }
public function addUser($name, $age) {
Test::setID();
Test::setNAME($name);
Test::setAGE($age);
echo "OK";
}
}
?>
I want to create objects of this class, and assign the data with the function addUser like this:
$test = new Test();
$test:: addUser("Peter", "12"); but I have errors.
I have this errors:
Strict Standards: Non-static method Test::addUser() should not be
called statically in /var/www/public/testManu.php on line 13
Strict Standards: Non-static method Test::setID() should not be called
statically in /var/www/public/class/Test.php on line 18
Fatal error: Using $this when not in object context in
/var/www/public/class/Test.php on line 8
I have problems with variable scope. Could somebody tell me what it is my problem????
change this:
...
public function addUser($name, $age) {
$this->setID();
$this->setNAME($name);
$this->setAGE($age);
echo "OK";
}
...
Calling like Classname::function() is only valid for static methods. You have a dedicated instance which need to be addressed with the construct $this->function().
And thus:
...
$test->addUser("Peter", "12"); but I have errors.
$test = new Test();
$test -> addUser("Peter", "12"); #now no errors
This should work for you:
<?php
class Test {
private static $_ID = 1;
private static $_NAME;
private static $_AGE;
public static function setID() { self::$_ID++; }
public static function getID() { return self::$_ID; }
public static function setNAME($element) { self::$_NAME = $element; }
public static function getNAME() { return self::$_NAME; }
public static function setAGE($element) { self::$_AGE = $element; }
public static function getAGE() { return self::$_AGE; }
public static function addUser($name, $age) {
self::setID();
self::setNAME($name);
self::setAGE($age);
echo "OK";
}
}
$test = new Test(); /*You don't need to instantiate the class
because you're calling a static function*/
$test:: addUser("Peter", "12"); but I have errors.
?>
Related
I am noob in PHP because I am mostly do .NET/Java. In code base I am working, I have,
class SomeOtherBaseClass{
public $prop2;
public function __construct(string $prop3)
{
$this->prop2 = $prop3;
}
public function __toString()
{
return $this->prop2 . ' '. $this->prop2;
}
}
class SomeClass
{
public function __toString()
{
return $this->prop1 . ' '. $this->prop1;
}
public $prop1;
public function someMethod() : SomeOtherBaseClass
{
return $this->createClass();
}
public function __construct()
{
$this->prop1 = 'foo';
}
private function createClass(
): SomeOtherBaseClass {
return new class(
$this->prop1
) extends SomeOtherBaseClass {
};
}
}
$class = new SomeClass();
echo $class;
echo $class->someMethod();
Why I am getting error that prop1 not found. Clearly createClass function is part of SomeClass which have prop1. Why I cannot access prop1 inside createClass?
It's because $prop1 has no value or meaning.
You can add a __construct() function to resolve your issue:
public function __construct()
{
$this->prop1 = 'foo';
}
now when you call this class (e.g. $foo = new SomeClass();):
$prop1 has a value of foo which can be used in your functions:
public function echoProp()
{
echo $this->prop1; # will output foo
}
Note: This is just an explanation answer - not a copy/paste solution - but the principles are all here for you to use in your code.
Let me know if this wasn't what you were looking for :)
Edit:
if prop1 exists in SomeOtherClass, when you construct you can do
public function __construct()
{
$this->class = new SomeClass();
$this->prop1 = $this->class->prop1;
}
Trying to use objects that extend singletone, but something I can't do.
How to call method from extended class?
How to show 13 non 12 with singleton?
class SingletonTest
{
protected static $_instance;
private function __construct(){}
private function __clone(){}
public static function getInstance() {
if (null === self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
public function test2(){
return 12;
}
}
class ExtendSingleton extends SingletonTest
{
public function test2() {
return 13;
}
}
$b = ExtendSingleton::getInstance();
echo $b->test2(); //12
You will get what you want if you use static binding keyword "static" instead of "self"
class SingletonTest
{
protected static $_instance;
private function __construct(){}
private function __clone(){}
public static function getInstance() {
if (null === static::$_instance) {
static::$_instance = new static();
}
return static::$_instance;
}
public function test2(){
return 12;
}
}
class ExtendSingleton extends SingletonTest
{
public function test2() {
return 13;
}
}
$b = ExtendSingleton::getInstance();
echo $b->test2(); //13
$a = SingletonTest::getInstance();
echo $a->test2(); //13
exit;
But as You see in the above example this way a class which You will call first to "getInstance" will take place to store its instance in the $_instance field.
There is no way to create a base singleton class and inherit singleton behavior.
public static function getInstance()
{
static $instances = array();
$calledClass = get_called_class();
if (!isset($instances[$calledClass]))
{
$instances[$calledClass] = new $calledClass();
}
return $instances[$calledClass];
}
So this should work for you:
(So first normally functions are public so you can use them if you extend from another class! And the you have to make an object from ExtendSingleton not from SingletonTest since ExtendSingleton exdend's -> SingletonTest and not the other way.)
<?php
class SingletonTest {
protected static $_instance;
public function __construct() {
}
public function __clone() {
}
public static function getInstance() {
if (null === self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
public function test2(){
return 12;
}
}
class ExtendSingleton extends SingletonTest {
public function test2() {
return 13;
}
}
$b = new ExtendSingleton();
echo $b->test2(); //13
?>
Output:
13
I've tested bicccio's solution and it works
class SingletonTest
{
protected static $_instances = [];
private function __construct(){}
private function __clone(){}
public static function getInstance()
{
$calledClass = get_called_class();
if (!isset(self::$_instances[$calledClass]))
{
self::$_instances[$calledClass] = new $calledClass();
}
return self::$_instances[$calledClass];
}
public function test2(){
return 12;
}
}
class ExtendSingleton extends SingletonTest
{
public function test2() {
return 13;
}
}
$b = ExtendSingleton::getInstance();
echo $b->test2(); //13
$a = SingletonTest::getInstance();
echo $a->test2(); //12
You can extend singleton class in php using late static binding the whole process is well discussed in this question.
Creating the Singleton design pattern in PHP5
I have the following class written for PHP 5.4.x. Should this work as I expect?
class SqlBuilder {
private $dbTable;
private $action;
private $data;
private $clause;
public function toString() {
// $sql = generate sql string
// [...]
return $sql;
}
[...]
public function setClause($clause) {
$this->clause = $clause;
}
public function setDbTable($dbTable) {
$this->dbTable = $dbTable;
}
public function setAction($action) {
$this->action = $action;
}
}
$sql = (new \dbal\SqlBuilder())
->setAction($this->action)
->setClause($this->clause)
->setDbTable($this->dbTable)
->toString();
I am expecting to be able to access all of my setter methods. Instead I see the following error:
Fatal error: Call to a member function toString() on a non-object )
This seems to work:
$builder= new \dbal\SqlBuilder();
$builder->setAction($this->action)
$builder->setClause($this->clause)
$builder->setDbTable($this->dbTable)
$sql = $builder->toString();
But I know that this works as well:
class Foo
{
public $a = "I'm a!";
public $b = "I'm b!";
public $c;
public function getB() {
return $this->b;
}
public function setC($c) {
$this->c = $c;
return $this;
}
public function getC() {
return $this->c;
}
}
print (new Foo)
->setC($_GET["c"])
->getC(); // I'm c!
I've used this style of syntax in Javascript before. Is there a way to make it work in PHP?
What you are asking about is called method chaining. In order for it to work the way you want, each method call needs to return a reference to the object that you are calling. So,
->setAction($this->action)
// needs to return $this; so that
->setClause($this->clause)
// knows what to operate upon and in turn needs to return $this; so that
->setDbTable($this->dbTable)
// can do the same
Try :
public function setClause($clause) {
$this->clause = $clause;
return $this;
}
public function setDbTable($dbTable) {
$this->dbTable = $dbTable;
return $this;
}
public function setAction($action) {
$this->action = $action;
return $this;
}
Bellow is a PHP script.
I tried to implement the Observer pattern (without MVC structure)... only basic.
The error which is encountered has been specified in a comment.
First I tried to add User objects to the UsersLibrary repository. There was a error such as User::update() does not exists or something.
Why is that error encountered? What fix should be applied and how?
interface IObserver {
public function update(IObservable $sender);
}
interface IObservable {
public function addObserver(IObserver $obj);
public function notify();
}
class UsersLibrary implements IObservable {
private $container;
private $contor;
//private $z;
public function __construct() {//IObserver $a) {
$this->container = array();
$this->contor = 0;
echo "<div>[constructing UsersLibrary...]</div>";
$this->addObserver(new Logger());
//$this->z = $a;
}
public function add($obj) {
echo "<div>[adding a new user...]</div>";
$this->container[$this->contor] = $obj;
$this->contor++;
$this->notify();
}
public function get($index) {
return $this->container[$index];
}
public function addObserver(IObserver $obj) {
$this->container[] = $obj;
}
public function notify() {
echo "<div>[notification in progress...]</div>";
foreach($this->container as $temp) {
//echo $temp;
#################################################################
$temp->update(); //--------ERROR
//Fatal Error: Call to a member function update() on a non-object.
#################################################################
}
//$this->container[0]->update();
//$this->z->update($this);
}
}
class User {
private $id;
private $name;
public function __construct($id, $name) {
$this->id = $id;
$this->name = $name;
}
public function getId() {
return $this->id;
}
public function getName() {
return $this->name;
}
}
class Logger implements IObserver {
public function __construct() {
echo "<div>[constructing Logger...]</div>";
}
public function update(IObservable $sender) {
echo "<div>A new user has been added.</div>";
}
}
$a = new UsersLibrary(); //new Logger());
//$a->add(new User(1, "DemoUser1"));
//$a->add(new User(2, "DemoUser2"));
$a->add("Demo");
echo $a->get(0);
//echo $a->get(0)->getName();
Your User class is not implementing interface IObserver and therefore is not forced to have the method update().
You have to instantiate a new User() in order to add it to the UsersLibrary:
$library = new UsersLibrary();
$user = new User(1, "Demo");
$library->add($user);
Also, you are mixing Users and Loggers into your UsersLibrary container. Maybe think about separating the containers for them?
You are passing a string instead of an object in your $a->add() call. You should either pass in an object, or alter the code in UserLibrary::add() to wrap it's argument in an appropriate object (or do an object lookup of it sees a string, for instance find a user with that name).
$user = new User(1, "Demo");
$a = new UsersLibrary();
$a->add($user);
class me {
private $name;
public function __construct($name) { $this->name = $name; }
public function work() {
return "You are working as ". $this->name;
}
public static function work() {
return "You are working anonymously";
}
}
$new = new me();
me::work();
Fatal error: Cannot redeclare me::work()
the question is, why php does not allow redeclaration like this. Is there any workaround ?
There is actually a workaround for this using magic method creation, although I most likely would never do something like this in production code:
__call is triggered internally when an inaccessible method is called in object scope.
__callStatic is triggered internally when an inaccessible method is called in static scope.
<?php
class Test
{
public function __call($name, $args)
{
echo 'called '.$name.' in object context\n';
}
public static function __callStatic($name, $args)
{
echo 'called '.$name.' in static context\n';
}
}
$o = new Test;
$o->doThis('object');
Test::doThis('static');
?>
Here is how I think you should do it instead:
class me {
private $name;
public function __construct($name = null) {
$this->name = $name;
}
public function work() {
if ($this->name === null) {
return "You are working anonymously";
}
return "You are working as ". $this->name;
}
}
$me = new me();
$me->work(); // anonymous
$me = new me('foo');
$me->work(); // foo