How can I get a public variable in PHPOO? [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to put a 'global' value in a PHP controller, because I use it constantly in different functions, so, I've to send it a lot of times in the view, I saw that I can do a public variable like an attribute in Java.
I have to declare the variable:
var $team="";// or public $team="";
How can I put, and get the value of the PHP attribute?

Class Example:
class MyClass
{
private $_a;
public $b;
public function __construct()
{
// example of constructor
}
public function set($a)
{
$this->_a = $a;
}
public function get()
{
return $this->_a;
}
}
Example of usage:
// usage construct class and invoke private function set();
$myExampleClass = new MyClass();
$myExampleClass->set('something');
// set public
$myExampleClass->b = "i set a public var";
It probably best to design your class with getters and setters so keeping your variables private, unless you have specific reasons. Here is a good reference for best practices and styleguide.
I hope this helps.

Related

Best way to restrict return value from interface in PHP [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 months ago.
Improve this question
I am developing an open source project in Laravel. I want to create framework which people can create their own payment gateways for their needs by implementing generic interfaces and ui will interact with that payment gateway. Which is the best way restrict return value from interface.
Right now I'm using this technic:
interface PaymentGateway
{
public function savePaymentPlan($email, $name, $surname, $phone, $cardNum, $cardHolderName, $cardExpriy, $amount, $checkoutDay): SavePaymentPlanResult;
}
interface SavePaymentPlanResultInterface{
public function getCardToken();
public function setCardToken($token);
}
class SavePaymentPlanResult implements SavePaymentPlanResultInterface{
private $cardToken = null;
public function setCardToken($token){
$this->cardToken = $token;
}
public function getCardToken(){
return $this->cardToken;
}
}
And using all of them like that:
class StrapiPaymentGateway implements PaymentGateway{
public function savePaymentPlan($email, $name, $surname, $phone, $cardNum, $cardHolderName, $cardExpriy, $amount, $checkoutDay): SavePaymentPlanResult {
$savePaymentPlanResult = new SavePaymentPlanResult;
...
...
$savePaymentPlanResult->setToken('<some-token>')
...
...
return $savePaymentResult;
}
}
Inside controller
class Controller {
test(){
$strapiPaymentGateway = new StrapiPaymentGateway();
$token = $strapiPaymentGateway->getToken();
}
}
Is it true way to do that? Because so many stuff you have to do just restrict return value?
Thanks for your answer.
Yes, defining the return type in the interface is the best way to enforce it.
However, if you want to be strict about coding towards an interface the savePaymentPlan method should return the SavePaymentPlanResultInterface instead of the concrete type. Then again, if you know you will only have one SavePaymentPlanResult, you don't necessarily need the SavePaymentPlanResultInterface.
On a side note: your naming is a bit inconsistent. You seem to add the Interface for interfaces, but then PaymentGateway interface is just called PaymentGateway.

Is it bad practice to call a static method via an object? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I found that calling the static method via object can be very convenient in some use case.
I'm wondering if this is is considered as a bad practice?
or if this feature will be removed in the future version of PHP?
class Foo
{
public static function bar ()
{
echo 'hi';
}
}
class SubFoo extends Foo
{
public static function bar ()
{
echo 'hi subfoo';
}
}
// The normal way to call a static method.
Foo::bar(); // => "hi"
// Call the static method via instance.
$foo = new Foo;
$foo::bar(); // => "hi"
// Here is the use case I found calling static method via instance is convenient.
function callbar(Foo $foo)
{
// The type-hinting `Foo` can be any subclass of `Foo`
// so I have to figure out the class name of `$foo` by calling `get_class`.
$className = get_class($foo);
$className::bar();
// Instead of the above, I can just do `$foo::bar();`
}
callbar(new SubFoo); // => "hi subfoo"
As a general rule, using static methods is bad practice because:
In fact, static methods or static variables are global variables
static code makes can cause many troubles in testing
static code makes high cohesion between parts of code
static code makes hidden dependencies between parts of code
But, there are cases when using static code is justified. For example:
Methods refer to a class and don't refer to objects
Helpers or Util classes which don't have their states

PHP Database class with singleton pattern [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Is it a good practice to create query function inside Database class (which must be created with singletone pattern). Or better create another class with database interface, or something like that, and get database instance in constructor? (Sorry for my English :)
<?php
class Database
{
private static $_pdo = null;
private static function getDatabase() {
if (self::$_pdo === null) {
self::$_pdo = new PDO("mysql:host=localhost;dbname=contact_manager", 'root', '');
}
return self::$_pdo;
}
public static function query($query, $parameters) {
Database::_toArray($parameters);
$query = self::getDatabase()->prepare($query);
$query->execute($parameters);
$result = $query->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
private static function _toArray(&$parameters) {
if (!is_array($parameters)) {
$parameters = array($parameters);
}
}
private function __construct() { }
private function __clone() { }
private function __wakeup() { }
}
?>
This is very wide theme is it good practice or not. As for me there're can be some points of view.
If you don't plan extend your project with another databases which queries should be called via same interface - this solution is OK
If we look at this from SOLID's point of view this is bad decision. According to SOLID you have to separate DB connection from queries. This is because of D-principle (dependency inversion) + S-principle (single responsibility). Also you have to define your own DatabaseInterface which you will use for injection your connection into Repositories - classes which encapsulate your DB queries.
However, this decision also depends on size of your project and your goal. If you just want to make everything right instead of inventing your own brand new bicycle, just take some framework like Symfony or Laravel and forget about this low-level stuff.

Php, code completion for factory methods? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
class A
{
public function method1() {}
public function method2() {}
}
class B
{
public function method1() {}
public function method3() {}
}
class Factory
{
public static function create($className)
{
return new $className();
}
}
and now when I try to use it:
Factory::create('A')->
Factory::create('B')->
Ide wont enumerate any methods, I cant add the appropiate phpdoc.
Of corse I can always wrap it:
/**
* #return A
*/
public static function createA()
{
return new A();
}
but thats not 100% satisfying, especially when I have tons of these.
If factory can return instances of different classes then all this classes should implement a common interface. In this case you should not care about actual class, but work with this interface.
If created objects should have different methods (which cannot be covered by generic interface), then obviously factory should have separate methods for every type of objects (or even separate factories).
If you really need for method with different types of return values, if type-safety is irrelevant and you only want to IDE autocompletion, then just add a doc-comment with multiple types like following (PHPStorm and NetBeans support this notation):
/**
* …
*
* #return A|B|C
*/

call class $this from external function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
inside a template php files, i have hundreds of such code:
echo str_replace('x','y', $this->load1->view('something'));
i have replaced that line everywhere, with code:
echo blabla();
and placed a function in my core library:
function blabla(){
return str_replace('x','y', $GLOBALS['this']->load1->view('something'));
}
but it triggers error: Fatal error...
In PHP, $this refers to the current object. For Example:
class MyClass {
protected $attribute;
public function method() {
$this->attribute;
}
public static function staticMethod() {
//$this is not available here because of the static context!
}
}
$this is used inside the MyClass.
For more details: http://php.net/manual/en/language.oop5.basic.php
Re: your edited question, $this only exists within the class.
You have two options:
function blabla($something){
str_replace('x','y', $something);
}
blablah($this->load1->view('something'));
Or, put function blabla() { inside the class, and drop the global $this line.

Categories