I need static class (object) to store a global variable value. I'm new in PHP but i have experience in other language that have OOP concept like in Java. In Java i can make static variable and can call anywhere i want. But how to do same in PHP?
I use CodeIgniter framework , before i try this i try using session to store but i want to use another way like above. can anyone help me?
Can i do like this ?
static class myClass{
public static myVar = "";
}
Because you mentioned framework Codeigniter and use of session I assume that you need to use this in multiple controller and views.
So I there is also another way which works bit different than property of class but more similar than session (except changed value won't affect on another page).
So Use Constant.
Define it in
application > config > constant.php
page. There are many constant defined in that page, using exact same syntax you can define your values and you can use it very easily to any where.
just like if you define SITE_NAME constant in constant.php as
defined('SITE_NAME') OR define('SITE_NAME', "My Example Site");
After that you can use it anywhere in any controller, view or model of your Codeigniter, What you need to do is just echo it
<?php echo SITE_NAME; //only SITE_NAME not $SITE_NAME ?>
I hope it is what you want, if not sorry for my misunderstanding.
You can have a static-like class in PHP. But you don't have an app-cycle in PHP. This means you won't get a real static (or singleton) in your whole application.
If you shouldn't be able to instantiate a class then it should be abstract and define its methods as static. However, somebody could just subclass the class and make it non-abstract. If you don't want that to be a possibility either then the class should be abstract final.
If you do this, you can call methods directly on the class in question with ClassName::methodName() syntax. Do bear in mind that classes written like this can't make use of $this because it is only valid for an object instance. If you need the class to maintain state then you will have to define a static variable and use it with self:: or static:: syntax.
abstract final class SomeClass
{
private static $var = "";
public static function setVar($newVal)
{
self::$var = (string) $newVal;
}
public static function getVar()
{
return self::$var;
}
}
A word of caution on doing this though, use of abstract classes/methods can very easily lead to tightly coupled code which is bad for a number of reasons.
For example, if you write a class that calls the methods of an abstract class directly by any means other than inheriting from the abstract class, then it will be impossible to unit test that class in isolation. It will always require your abstract class to be part of the test suite too, which means it's more difficult to determine whether a test failure has been caused by a fault in the class under test or in the abstract class it's depending on.
What's more, if the abstract class you're depending on serves as an accessor for a data source, then you also will not be able to mock the class during tests. Mocking is a very powerful way of verifying the correctness of a class without having to rely on the environment that the class is running in. for example, you can mock a database access class with a compatible object that always returns the same data from an array instead of hitting an actual database. This means that you can guarantee that when you run a test it will run with data in a state that you have full control over. If you access a database via an abstract class's methods then you can't replace that for testing and suddenly you may end up with a test suite that might succeed or fail depending on the state of the database at the time you run the test. Even worse, if your tests involve writing to the database then you could potentially corrupt your data source when running tests.
Related
As I looked for the new PHP7-features I stumbled upon anonymous classes.
I didn't understand when they should become useful, and looked for an example.
I read this article, but I don't see the benefits of this feature.
In the last section before the conclusion they wrote the following about the advantages:
One advantage is that we no longer need the named extension. Normally the named extension would be hidden away in some included file, if you ever needed to see how it is defined you have to start searching for it. With anonymous classes the definition is in the same place the object is created.
On the other hand, I see a big disadvantage because you can use this anonymous class only at the place it is defined.
Can someone please explain when this feature is useful?
Especially if it can help when building custom systems or extending a CMS like WordPress (preferably in German, although English is also welcome).
Anonymous classes could be useful in writing implementation classes for listener interfaces, so you don't need to create a file or a generic class just to implement once.
One of the most elegant things about anonymous classes is that they
allow you to define a one-shot class exactly where it is needed. In
addition, anonymous classes have a succinct syntax that reduces
clutter in your code. Java in a nutshell
So, you can have an anonymous implementation of an interface or even extend a class, with additional properties or overwritten methods.
Example:
return new class(10) extends SomeClass implements SomeInterface {
private $num;
public function __construct($num)
{
$this->num = $num;
}
};
Another situation:
Provide a simple implementation of an adapter class. An adapter class is one that defines code that is invoked by some other object. Take, for example, the list() method on a class called File. This method lists the files in a directory. Before it returns the list, though, it passes the name of each file to a FilenameFilter object you must supply. This FilenameFilter object accepts or rejects each file. When you implement the FilenameFilter interface, you are defining an adapter class for use with the $file->list() method. Since the body of such a class is typically quite short, it is easy to define an adapter class as an anonymous class.
$file = new File("/src");
// Now call the list() method with a single FilenameFilter argument
// Define and instantiate an anonymous implementation of FilenameFilter
// as part of the method invocation expression.
$filelist = $file->list(new class extends FilenameFilterClass {
public function accept(File $f, string $otherInfo) {
return pathinfo($f, PATHINFO_EXTENSION) === ".php";
}
});
Some nice basic understanding and use about anonymous classes could be found on Java (I know its not PHP, but it helps on understanding) examples at https://www.geeksforgeeks.org/anonymous-inner-class-java/
I should use a anonymous class only if this class is not used anywhere else and if these class isn't changed since the first coding.
So for example a database class could maybe a candidate for using a anonymous class because it should be use only once and could be included in any other php file. In most cases the data for accessing the database is in the config file. Therefore this file should be loaded for every php file that is using the database when you want to avoid the hard coding of the database params (which is a bad idea). If you coded these class as an anonymous class in the config file you have eliminated one include whithout losing the maintainance.
It is OK to have methods depend one on each other inside a class, methods that are encapsulated together? Does this affect unit testing? or the term Unit is addressing to the whole class and not to the class own methods.
It is OK to do something like this:
<?php
class foo {
protected $baz;
protected $bar;
private function checkBaz($baz) {
// do some checking
}
private function checkBar($bar) {
// do some checking
}
public function setBaz($baz) {
if($this->checkBaz($baz)){
$this->baz = $baz;
}
}
public function setBar($bar) {
if($this->checkBar($bar)){
$this->bar = $bar;
}
}
}
I'm thinking if I want to use a bound method from this class to another class I have to rewrite the method a little bit, I was wandering if it is overhead to make methods somehow encapsulated like inserting functionality in to method parameters, Is this a common practice in OOP or should I stick to the thinking that a class is an encapsulation of high cohesion method and properties and see it like a whole reusable and testing Unit.
Yes, calling methods internally in a class is absolutely fine. In fact, it's encouraged. The mere presence of protected and private methods should be a dead giveaway. You can only call those from within the class, from somewhere that needs to be triggered by a public method, so yes, your example if perfectly in line with how those methods are supposed to be used.
The only thing that matters in general and in terms of unit testing is how the object as a whole behaves. Its public components are important, that's what other code interacts with and it's what other code observes. Whatever kinds of internal calls your object/class makes is perfectly up to its own discretion. If it helps your class structure to put certain code in separate methods and hide them from the outside world, so be it.
Yes, performing method calls like this is perfectly fine. They're marked as private so they remain encapsulated within your class and unexposed to the outside world.
If these method calls started to cause the class/object to deviate its main purpose, breaking single responsibility principle, then it would be worth looking at breaking the class into finer units and injecting this new dependency via dependency injection. An example of this would be if the checkBaz method was performing a database look-up.
In terms of unit testing, what you really want to do is program to an interface not implementation by creating an interface for your foo class and implementing it. This means whenever you program to it you're programming to a contract - allowing you to easily mock your IFoo implementation.
eg:
class Foo implements IFoo {
}
Your interface will look like this:
interface IFoo
{
public function setBaz($baz)
public function setBar($bar)
}
I would also recommend following the PEAR coding standard and make your class names uppercase first. Though if this is a decision made by you or your team then that's entirely your call.
There's nothing wrong with non-public methods. In fact, a class should only export the bare minimum of public methods to allow other classes to make use of its services. The more external classes know about the inner workings of your class, the more difficult it is to make changes to the inner workings of your class without upsetting external dependencies.
The non-public methods should be tested by being called indirectly. There should be a circumstance under which every method gets called eventually, even if it's through indirect calling (public method calls private method, etc). If a method is never executed in a unit test then that's a good indicator that it is in fact dead code and can be removed from the class altogether.
You can in theory directly test the protected methods of a class by subclassing it and elevating the protected methods to public, but that's not recommended because it exposes internal workings of your class and you don't really want to do that.
I am new to OO concepts in PHP. I have a class called MY_ controller which is my base class. All classes extend this class. I am using MVC architecture. I am using caching in my system now. So i load the cache variable in the constructor of my base class. I use normal php variable like $cacheVariable in my function to store the value from cache. I was wondering if it would serve any help if i store it as a class parameter and use like $this->cacheVariable? In each function i get cache value like $this->cache->get('cacheVariable'); will it help if i get value from $this->cacheVariable
If you want to be able to use $cacheVariable anywhere else besides your constructor you'll want to use $this
public function __construct() {
//...
$this->cacheVariable = $this->cache->get('cacheVariable');
//...
}
Also remember, if you want your children classes to inherit this variable from your base class you will need to set it as either public or protected. If it's private children will not inherit it.
When you say "class variable" I assume you are referring to a property (property of an instance=. Note the difference:
if you have a class, say MyClassA, then in your scripts you will instantiate that class using the operator new (depending on your PHP version you can use a different constructor syntax it changed since PHP-5.3.0):
<?php
class MY_controller{
public $cacheVariable;
// constructor
function MY_controller($aValue){
// constructor code which loads cacheVariable, for example with parameter
$this->cacheVariable = $aValue;
}
public function someFunction(){
//... some code, then access the property
$cv = $this->cacheVariable;
}
}
$aController = new MY_controller(42);
?>
As you inherit from MY_controller, every instance of that class, will have access to cacheVariable through $this->cacheVariable.
The important thing I wanted to clarify is that it is an instance property, not a class one. For further reference on OOP in PHP, refer to the properties section in PHP's OOP manual and the inheritance section.
When you instantiate only one instances of your controller (derived from your main controller), its a conceivable solution.
In my opinion the better idea is getting variable directly from cache service everywhere you want in your class and don't keep it as a class property. The reason is simple: let's say value of some key from cache will be changed (or expires) in the other place than your class. If you have this value as class property you need to keeping eye on it every time you access this value but if you retrieving it from cache you just don't care (because the cache cares if value of some key doesn't changed or expired).
I understand that singleton enforces a class to be created once. But why should an instance exists if I dont access it directly? Why is that pattern for, isn't it easier just use full static class with static methods and datas?
Some time ago I was asked what is the benefit of using singleton over of using static class, here is my response:
Static class leads to invisible dependencies - that is a class that use the static class, but that class is not part of the class' interface.
Singleton also allows this, because it provides global access point, but it's instance can be passed as an argument to the class / method
If there is any initialization, as the connect method, it should be called from each class method, which leads to duplicated code. On the other hand, the initialization of the singleton is performed in the constructor, which is called just once from the getInstance()
method
Singleton can be easily refactored in a factory, adding a parameter to the getInstance() method and returning different instances
Static class is harder to extend, because if we want to override a method, that is called within the class with self::methodName(), we should override the caller as well (although in PHP 5.3 there is a late static binding, which can be used to avoid those problems)
If you need to add an argument, needed for all of the methods, you can easily do this in singleton because of the single access point, but you can't in a static class
The major difference between a static class and a singleton is that with the static class, you need to hardcode the class name in your code everywhere you use it:
StaticClass::doSomething();
StaticClass::doSomethingElse();
While with a singleton, you only need to hardcode the class name once:
$singleton = SingletonClass::getInstance();
// other code does not need to know where $singleton came from,
// or even that class SingletonClass exists at all:
$singleton->doSomething();
$singleton->doSomethingElse();
Another important difference is that singleton classes can be part of hierarchies and can implement interfaces.
This does not mean that Singleton (the pattern) is good and should be used liberally. But it is better than using a static class directly.
[Edit]: The stuff I have written below is actually plain wrong. Just got alerted to this answer from years ago by a downvote. They do serve a purpose ;)
A singleton exists once, but it can have internal state - as opposed to a static class. You might e.g. use it as a global registry, which you can't do with a static class.
[Edit:] What comes next, though, is as true as it ever was.
It's debatable whether singletons are a good idea, though. They introduce global state into an application, which can make it very hard to test. But that is another discussion.
Writing a PHP app and have several classes that only have static methods (no need for instance methods). An example of one is NumericValidator, which has methods like checkInteger($toCheck) which checks to make sure the argument you pass it is of type int, and checkGreaterThan($lOperand, $rOperand), which makes sure that the left operand is greater than the right operand, etc.
I know I could just throw each of these methods into a PHP file without putting them inside of a class, but I want to take an OOP approach here in case the API evolves to require instantiating NumericValidator.
But it does beg the question: how is a class with 100% static methods any different than have a class implement a singleton design pattern, where every reference used throughout the code base invokes the same instance?
For example, here is what my code looks like now:
public function doSomething($p_iNum)
{
if(!NumericValidator::checkInteger($p_iNum))
// throw IllegalArgumentException
// ...
}
But I could turn all of NumericValidator's static methods into non-static instance methods, forcing the programmer to instantiate it, and then implement a singleton design pattern so you can only ever reference 1 instance of it:
public function doSomething($p_iNum)
{
NumericValidator $nv = NumericValidator::getInstance();
if(!nv->checkInteger($p_iNum))
// throw IllegalArgumentException
// ...
}
Finally, my question: which is better and more in keeping with best practices? Are there performance considerations? How would either approach affect things like concurrency, or requests coming from multiple users?
I would use a static class in your example. The differentiator I would use is if there is any state of the properties of an instance you are trying to preserve across access. This is what a singleton is designed for. The static class gives organized access to methods in a namespace which is helpful for clarity in your code but it does not have any properties about itself.
So yes you can use a singleton but it would be bad form because there are no instance properties that you want to make available across page accesses.
Hope this helps.
Use Singleton instead of static class only if you going to pass instance of NumericValidator in variable to some function.
In PHP 5.3 you can get instance of static class:
class test
{
public static function instance()
{
print 'zz';
}
}
$z = new test;
$z->instance();
Don't care about concurrency requests in PHP, it's single threaded, each process executes own code.