Fatal error uncaught error access to undeclared static property

I've been attempting to play with this dicecalculator found here: https://github.com/ringmaster/dicecalc Previously everything functioned as expected, I could "roll" 3d6, 3d6+2, 1d12, etc without...

I’ve been attempting to play with this dicecalculator found here:
https://github.com/ringmaster/dicecalc

Previously everything functioned as expected, I could «roll» 3d6, 3d6+2, 1d12, etc without any problems.

After upgrading my vps to Ubuntu 16.04 with php7 on it, I started to receive the following error:

mod_fcgid: stderr: PHP Fatal error: Uncaught Error: Access to undeclared static property: DiceCalcCalcOperation::$operators in /public_html/dice/src/DiceCalc/CalcOperation.php:34

I’ve done a few searches on Access to undeclared static property to no avail. I’ve tried returning static:: on each of them. Here’s the CalcOperation.php it’s referencing:

<?php
/**
 * Class CalcOperation
 *
 * @package DiceCalc
 * @author  Owen Winkler <epithet@gmail.com>
 * @license MIT http://opensource.org/licenses/MIT
 */
namespace DiceCalc;
class CalcOperation {
    /**
     * @param  string $operator
     * @param $operand2
     * @param $operand1
     *
     * @throws Exception
     * @return bool|number
     */
    public function calc($operator, $operand1, $operand2) {
        $operators = array(
            '+' => 'add',
            '*' => 'multiply',
            '=' => 'equalto',
            '<' => 'lessthan',
            '>' => 'greaterthan',
            '^' => 'exponent',
            '/' => 'divide',
            '-' => 'subtract'
        );
        if (isset($operators[$operator])) {
            return self::$operators[$operator](self::reduce($operand1), self::reduce($operand2));
        }
        throw new Exception('Unknown operator "' . $operator . '".');
    }
    /**
     * @param $operand
     *
     * @return number|string
     * @throws Exception
     */
    public function reduce($operand) {
        if (is_numeric($operand)) {
            return $operand;
        } elseif ($operand instanceof Calc) {
            return $operand();
        }
        throw new Exception('This is not a number');
    }
    /**
     * @param  number      $operand1
     * @param  number      $operand2
     *
     * @return bool|number
     */
    public function add($operand1, $operand2) {
        return $operand1 + $operand2;
    }
    /**
     * @param  number      $operand1
     * @param  number      $operand2
     *
     * @return bool|number
     */
    public function multiply($operand1, $operand2) {
        return $operand1 * $operand2;
    }
    /**
     * @param  number      $operand1
     * @param  number      $operand2
     *
     * @return bool|number
     */
    public function subtract($operand1, $operand2) {
        return $operand1 - $operand2;
    }
    /**
     * @param  number    $operand1
     * @param  number    $operand2
     *
     * @return bool|number
     */
    public function divide($operand1, $operand2) {
        return $operand1 / $operand2;
    }
    /**
     * @param  number      $operand1
     * @param  number      $operand2
     *
     * @return bool|number
     */
    public function exponent($operand1, $operand2) {
        return pow($operand1, $operand2);
    }
    /**
     * @param  number $operand1
     * @param  number $operand2
     *
     * @return bool
     */
    public function greaterthan($operand1, $operand2) {
        return $operand1 > $operand2;
    }
    /**
     * @param  number $operand1
     * @param  number $operand2
     *
     * @return bool
     */
    public function lessthan($operand1, $operand2) {
        return ($operand1 < $operand2);
    }
    /**
     * @param  number $operand1
     * @param  number $operand2
     *
     * @return bool
     */
    public function equalto($operand1, $operand2) {
        return ($operand1 == $operand2);
    }
}

And here’s the line that calls the class:

$stack[] = CalcOperation::calc($step, $r2, $r1);

I’m just beginning to wrap my head around classes etc so I’m not sure how to fix this. I’ve tried switching the return self:: to return static:: among a few other things I’ve found by searching on here. I’m just stuck now. Anyone able to help?

Fatal error: Uncaught Error: Access to undeclared static property applicationmodelsAccount::$db in E:ITOpenServerdomainsbookshopapplicationmodelsAccount.php:9 Stack trace: #0 E:ITOpenServerdomainsbookshopapplicationcontrollersAccountController.php(31): applicationmodelsAccount::addUser() #1 E:ITOpenServerdomainsbookshopapplicationcoreRouter.php(58): applicationcontrollersAccountController->signupAction() #2 E:ITOpenServerdomainsbookshopindex.php(16): applicationcoreRouter->run() #3

thrown in E:ITOpenServerdomainsbookshopapplicationmodelsAccount.php on line 9

Signup.php (примитивный класс регистрации)

AccountController.php

Account.php

Model.php

Db.php

1 ответ 1

Выберите, что подходит для вас из списка ниже и почините ошибку:

  • К нестатическим публичным свойствам и методам класса за их пределами и за пределами наследников можно обращаться только после создания экземпляра с помощью стрелочки -> . Например (new User)->test() ;
  • К нестатическим свойствам и методам класса внутри этого класса можно обращаться с помощью ключевого слова $this и стрелочки -> . Например $this->test() ;
  • К нестатическим публичным/защищённым свойствам и методам родителя внутри наследника можно обращаться с помощью ключевого слова $this и стрелочки -> . Например $this->test() ;
  • К статическим публичным свойствам и методам класса за их пределами и за пределами наследников можно обращаться синтаксисом: ИМЯ_КЛАССА::ИМЯ_СВОЙСТВА или ИМЯ_КЛАССА::ИМЯ_МЕТОДА. Например User::$name или User::test()`
  • К статическим публичным свойствам и методам класса внутри этого класса можно обращаться синтаксисом: self::ИМЯ_СВОЙСТВА или self::ИМЯ_МЕТОДА static::ИМЯ_СВОЙСТВА или static::ИМЯ_МЕТОДА . Например self::$db или self::getName()
  • К статическим публичным/защищённым свойствам и методам родителя внутри наследника класса можно обращаться синтаксисом: self::ИМЯ_СВОЙСТВА или self::ИМЯ_МЕТОДА static::ИМЯ_СВОЙСТВА или static::ИМЯ_МЕТОДА . Например self::$connection или self::logout()

Источник

Uncaught Error: Access to undeclared static property: Phalcon\Di::$_default #12803

It works fine with PHP 5.6 but when I upgrade to PHP7 this error happens

Uncaught Error: Access to undeclared static property:
PhalconDi::$_default bootstrap_web.php.

Details

  • Phalcon version: 3.1.2
  • PHP Version: PHP 7.0.15 (cli) (built: Feb 27 2017 23:58:56) (Zend Engine v3.0.0 ,with Zend OPcache v7.0.15,)
  • Operating System: CentOS Linux release 7.3.1611 (Core)
  • Installation type: Compiling from source
  • Server: Apache and Compiling from source
  • Other related info (Database, table schema): DB Mysql 5.7

The text was updated successfully, but these errors were encountered:

@mohamedziada Could you please provide script / steps to reproduce?

Something similar in #12056

If @mohamedziada used Windows — yes

Can you reproduce with OPcache disabled? Do you use ApcMetaData?
Can you reproduce running test case provided by renatomjr: #12056 (comment) ?

ownCloud users are experiencing similar issue with PHP 7 on linux (openSUSE) too :
https://www.bountysource.com/issues/30829375-access-to-undeclared-static-property-oc-files-filesystem-normalizedpathcache
So, it might be possible that it’s not only Windows issue.

EDIT: in case of ownCloud, the issue seems to appear when there are some aborted requests/connections. We could also try a similar test case like suggested in the ownCloud thread:
https://pastebin.com/Ywhjx5hq

@hakimio but this test case doesn’t have phalcon calls so how it’s phalcon issue?

Источник

Uncaught Error: Access to undeclared static property: OC\Files\Filesystem::$normalizedPathCache in filesystem.php #23804

Steps to reproduce

  1. share a directory with some .mp4 files
  2. play on iphone

Expected behaviour

The video should play

Actual behaviour

Nothing happens when clicking the play video

Server configuration

Operating system:
centos 7.2.1511

Web server:
apache 2.4.6-40.el7

Database:
mariadb-5.5.47-1.el7_2

PHP version:
php-7.0.5-1.el7.remi

ownCloud version: (see ownCloud admin page)
owncloud-files-9.0.0-3.1.noarch

Updated from an older ownCloud or fresh install:
updated

Signing status (ownCloud 9.0 and above):

No errors have been found.
List of activated apps:

The content of config/config.php:

Are you using external storage, if yes which one: local/smb/sftp/.
no

Are you using encryption: yes/no
no

Are you using an external user-backend, if yes which one: LDAP/ActiveDirectory/Webdav/.
no

Client configuration

Browser:
Iphone

Operating system:
IOS9

Web server error log

ownCloud log (data/owncloud.log)

Browser log

No idea on how I could get that on IOS

The text was updated successfully, but these errors were encountered:

I’m seeing this error trying to connect a (Linux) sync client on a new machine to an existing account on a Linux ownCloud server. It gets a ways through the process of looking for what to sync and them bombs out.

I’ve got the same issue, don’t know what causes it.

I can confirm this. Issue appeared for me when updating PHP-FPM and related packages from 7.0.5 to 7.0.6 on CentOS 7. Downgrading back to 7.0.5 resolved the issue.

Edit: this is using the Remi PHP7 Repo.

My error went away when I upgraded the ownCloud server from sqllite to mysql and added redis as a memory cache. I don’t know if this is direct (e.g. an error that is only in the sqlite code somewhere) or secondary (e.g. some sort of race condition and redis is fast enough I’m not hitting it any more) but the correlation is pretty solid. I was getting the error on every sync operation for weeks, then upgraded the above two items and now for a week all my syncs have succeed.

I’ve always used a MySQL backend. I currently have no caching setup, redis or otherwise. When I updated PHP to 7.0.6 I was unable to login at all.

Edit:: Applying https://github.com/owncloud/core/pull/24343/files appears to have resolved my problems.

I am experiencing the same issues as @tfmm. Upgraded from PHP 7.0.5 to 7.0.6 from ondrej’s PPA and have observed the following behavior:

  1. Little to no information is reaching the log, even at the DEBUG level. Only cronjob completions reached the file. No user login events or anything reached the file.
  2. All DAV resources are returning 404s to clients.
  3. I am unable to log in, and am immediately redirected back to the same URI with a login page and no displayed error messages.

ownCloud version:
9.0.1 (same version as before issue occurred) — integrity OK

OS:
Ubuntu 15.10

Apache:
Apache/2.4.12 (Ubuntu)

MySQL version:
Ver 15.1 Distrib 10.0.23-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2

PHP version:
PHP 7.0.6-1+donate.sury.org

wily+1 (cli) ( NTS ) from ondrej PPA

Redis (compiled) version:
Redis server v=3.0.7 malloc=jemalloc-3.6.0 bits=64 build=fd6caf34ab0dc5e7

Client:
Appears irrelevant. OS X and iOS Contacts app, Chrome (latest), Firefox (latest), ownCloud client Version 2.1.1 (build 3107) (OS X).

Источник

Fatal error: Uncaught Error: Access to undeclared static property: PhalconDi::$_default #12065

Fatal error: Uncaught Error: Access to undeclared static property: PhalconDi::$_default in D:OpenServerdomainsbca.locpublicindex.php:18 Stack trace: #0 [internal function]: PhalconDi->__construct() #1 D:OpenServerdomainsbca.locpublicindex.php(18): PhalconDiFactoryDefault->__construct() #2 D:OpenServerdomainsbca.locpublicindex.php(92): Application->registerServices() #3 D:OpenServerdomainsbca.locpublicindex.php(112): Application->main() #4

Next Error: Access to undeclared static property: PhalconDi::$_default in D:OpenServerdomainsbca.locpublicindex.php:18 Stack trace: #0 [internal function]: PhalconDi->__construct() #1 D:OpenServerdomainsbca.locpublicindex.php(18): PhalconDiFactoryDefault->__construct() #2 D:OpenServerdomainsbca.locpublicindex.php(92): Application->registerServices() #3 D:OpenServerdomainsbca.locpublicindex.php(112): Application->main() #4
thrown in D:OpenServerdomainsbca.locpublicindex.php on line 18

The error appeared after migrating from phalcon 2.1.0 RC 1 on php 5.6 to phalcon 3.0.0 on Php-7

The system: Windows 10
Server: Open Server
PhpVersion: Php-7-x64
PhalconVersion: 3.0.0

Reproduce:
Open the page, that making curl request to remote server, go to other page => got fatal error. Update page => no fatal error.

The error appeared in public/index.php

The text was updated successfully, but these errors were encountered:

Источник

Uncaught Error: Access to undeclared static property — NC 9 #34

I have at ussage of the audioplayer app the following errors in admin log:

Uncaught Error: Access to undeclared static property: OCFilesFilesystem::$normalizedPathCache in /var/www/htdocs/lib/private/files/filesystem.php:798 Stack trace: #0 /var/www/htdocs/lib/private/files/view.php(2011): OCFilesFilesystem::normalizePath(‘/MaT/files/Musi. ‘) #1 /var/www/htdocs/lib/private/files/view.php(1129): OCFilesView->unlockFile(‘/Music — World/. ‘, 1) #2 [internal function]: OCFilesView->OCFiles() #3 /var/www/htdocs/3rdparty/icewind/streams/src/CallbackWrapper.php(109): call_user_func(Object(Closure)) #4 [internal function]: IcewindStreamsCallbackWrapper->stream_close() #5

thrown at /var/www/htdocs/lib/private/files/filesystem.php#798

My config: Debian 8, NC 9.0.53, PHP 7, Apache 2.4

Thx for feedback & resolve 🙂

The text was updated successfully, but these errors were encountered:

Can you please retry the current 1.1.0
It was trsted with NC

i have upgraded today — but still error reports when i use the app — in frontend it works perfect — but the logfile is full with this errors:

Uncaught Error: Access to undeclared static property: OCFilesFilesystem::$normalizedPathCache in /var/www/htdocs/lib/private/files/filesystem.php:798 Stack trace: #0 /var/www/htdocs/lib/private/files/view.php(2011): OCFilesFilesystem::normalizePath(‘/MaT/files/Musi. ‘) #1 /var/www/htdocs/lib/private/files/view.php(1129): OCFilesView->unlockFile(‘/Music — World/. ‘, 1) #2 [internal function]: OCFilesView->OCFiles() #3 /var/www/htdocs/3rdparty/icewind/streams/src/CallbackWrapper.php(109): call_user_func(Object(Closure)) #4 [internal function]: IcewindStreamsCallbackWrapper->stream_close() #5

thrown at /var/www/htdocs/lib/private/files/filesystem.php#798

thanks in advance for your feedback 😉

Hello,
just got the same in my error log for the first time.
. trying to reproduce it.

Hello,
it seems to be an issue in some core functionality in relation to PHP7.
it is discussed here
owncloud/core#22370

Unfortunately I cant help you from audioplayer perspective 🙁

Источник

@k1T4eR

Expected and Actual Behavior

Describe what you are trying to achieve and what goes wrong.
Fetching record from table. Works on 3.2.12.

Provide output if related

PHP Fatal error:  Uncaught Error: Access to undeclared static property: NewMigration_101::$_connection in /var/www/html/test-api/app/migrations/1.0.1/new.php:80

Provide minimal script to reproduce the issue

if (!self::$_connection->fetchOne(
                "SELECT * FROM test WHERE name LIKE :name",
                PhalconDb::FETCH_ASSOC,
                [
                    "name" => $name,
                ])) {

Details

  • System info and versions (if possible): (phalcon info)
    Phalcon DevTools (3.4.0)
    Environment:
    OS: Linux 6801fde352f6 4.9.0-6-amd64 Easier installation on Linux and OSX #1 SMP Debian 4.9.82-1+deb9u3 (2018-03-02) x86_64
    PHP Version: 7.0.27-1+ubuntu16.04.1+deb.sury.org+1
    PHP SAPI: cli
    PHP Bin: /usr/bin/php7.0
    PHP Extension Dir: /usr/lib/php/20151012
    PHP Bin Dir: /usr/bin
    Loaded PHP config: /etc/php/7.0/cli/php.ini
    Versions:
    Phalcon DevTools Version: 3.4.0
    Phalcon Version: 3.3.1
    AdminLTE Version: 2.3.6

  • Phalcon Framework version: (php --ri phalcon)
    Version => 3.3.1

  • PHP Version: (php -v)
    PHP 7.0.27-1

  • Operating System:
    Linux version 4.9.0-6-amd64 (debian-kernel@lists.debian.org) (gcc version 6.3.0 20170516 (Debian 6.3.0-18+deb9u1) ) Easier installation on Linux and OSX #1 SMP Debian 4.9.82-1+deb9u3 (2018-03-02)

  • Server: Nginx | Apache | Other
    Server version: Apache/2.4.18 (Ubuntu)

@sergeysviridenko

@k1T4eR Could you provide a bit more information, steps to reproduce?

@sergeyklay

Right. There is no $_connection parameter. To create a sql query to the database you’ll need to create or get pdo connection.

@amnuts

Has this changed, though? I am able to run migrations just fine with devtools 3.2.11 but the same migrations using devtools 3.4.0 gives errors such as:

PHP Fatal error:  Uncaught Error: Access to undeclared static property: AccountAbilitiesMigration_113::$_connection in /vagrant/service/identity/migrations/1.1.3/account_abilities.php:19
Stack trace:
#0 /home/vagrant/phalcon-devtools/scripts/Phalcon/Mvc/Model/Migration.php(488): AccountAbilitiesMigration_113->up()
#1 /home/vagrant/phalcon-devtools/scripts/Phalcon/Migrations.php(297): PhalconMvcModelMigration::migrate(Object(PhalconVersionIncrementalItem), Object(PhalconVersionIncrementalItem), 'account_abiliti...')
#2 /home/vagrant/phalcon-devtools/scripts/Phalcon/Commands/Builtin/Migration.php(143): PhalconMigrations::run(Array)
#3 /home/vagrant/phalcon-devtools/scripts/Phalcon/Script.php(117): PhalconCommandsBuiltinMigration->run(Array)
#4 /home/vagrant/phalcon-devtools/scripts/Phalcon/Script.php(151): PhalconScript->dispatch(Object(PhalconCommandsBuiltinMigration))
#5 /home/vagrant/phalcon-devtools/phalcon.php(76): PhalconScript->run()
#6 {main}
  thrown in /vagrant/service/identity/migrations/1.1.3/account_abilities.php on line 19

So I wouldn’t outright claim it’s not a bug because it was working but now is not. If it was never meant to work then perhaps document how people need to migrate their migrations so that they continue to work as expected. (Or if it’s already documented, point us in the right direction?)

@AnatolyAstapov

in 3.4 found … they has renamed =)
in migration
self::$connection->query(«SELECT * FROM subscriptions»)->fetchAll();

@k1T4eR

in 3.4 found … they has renamed =)
in migration
self::$connection->query(«SELECT * FROM subscriptions»)->fetchAll();

Correct, thanks.

DeathAngel

9 / 9 / 5

Регистрация: 17.02.2012

Сообщений: 177

1

30.05.2018, 13:17. Показов 7089. Ответов 5

Метки нет (Все метки)


PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class View {
    var $template = null;
    protected $vars = array();
    protected $blocks = array();
    protected $result = array(
        'info' => '',
        'content' => ''
    );
 
    static function getInstance() {
        if(is_null(self::$instance)) {
            new self();
            $instance = true;
        }
 
        return $instance;
    }
    
    ***
}
 
$tpl = View::getInstance();

Ругается на:
Fatal error: Access to undeclared static property: View::$instance in D:***class.view.php on line 16

Подскажите плиз.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

30.05.2018, 13:17

5

Зверушь

461 / 369 / 94

Регистрация: 01.05.2010

Сообщений: 1,761

30.05.2018, 13:37

2

Добавь свойство

PHP
1
protected $instance = null;



0



9 / 9 / 5

Регистрация: 17.02.2012

Сообщений: 177

30.05.2018, 13:41

 [ТС]

3

Зверушь, не помогло.



0



tarasalk

1980 / 1204 / 440

Регистрация: 13.06.2013

Сообщений: 4,091

30.05.2018, 15:17

4

PHP
1
protected static $instance = null;

И в методе getInstance бред.
Если правильно уловил мысль, должно быть так

PHP
1
2
3
4
5
6
7
static function getInstance() {
        if(is_null(self::$instance)) {
            self::$instance = new self();
        }
 
        return self::$instance;
    }

Не по теме:

Если вдруг свой MVC пишите, увы, рано.:scratch:. Сначала надо научиться такие ошибки исправлять.



0



3 / 3 / 0

Регистрация: 27.07.2011

Сообщений: 21

23.04.2021, 15:52

5

Ошибка в 11 стр-ке self::$instance — не объявлена / public static $instance



0



Эксперт PHP

5743 / 4127 / 1503

Регистрация: 06.01.2011

Сообщений: 11,269

23.04.2021, 15:58

6

dukuu-sok0l, tarasalk три года назад уже ответил, как бы.

Цитата
Сообщение от dukuu-sok0l
Посмотреть сообщение

не объявлена / public static $instance

Не надо тут public.



0



Hey guys,

I’m quite new to PrestaShop and I’m pretty stumped on this one issue (The rest of the software has been fantastic thus far)… Here’s a quick rundown:

How the issue/error can be recreated: I go to a tab in the preferences, product in my case, and I make a change to a field (Such as «Show add to cart…»). I then click save underneath that section of options and the error occurs!

What I have done to fix it:  I have deleted all the cache files I have been instructed to by other forum posts and guides and I even disabled Smarty cache, but it seems like I am the only one with this error occurring on this exact admin page!

Exact error message: 

Fatal error: Uncaught Error: Access to undeclared static property: Validate::$values in 
/home2/crazyape/public_html/PShop/classes/controller/AdminController.php:1224 Stack trace: 
#0 /home2/crazyape/public_html/PShop/classes/controller/AdminController.php(765): 
AdminControllerCore->processUpdateOptions() #1 /home2/crazyape/public_html/PShop/classes/
controller/Controller.php(171): AdminControllerCore->postProcess() #2 /home2/crazyape/
public_html/PShop/classes/Dispatcher.php(373): ControllerCore->run() #3 /home2/crazyape/
public_html/PShop/admin-1495599749/index.php(54): DispatcherCore->dispatch() #4 {main} 
thrown in /home2/crazyape/public_html/PShop/classes/controller/AdminController.php on line 1224

^ Split into multiple lines for ease of scrolling, whole line posted here: 

Fatal error: Uncaught Error: Access to undeclared static property: Validate::$values in /home2/crazyape/public_html/PShop/classes/controller/AdminController.php:1224 Stack trace: #0 /home2/crazyape/public_html/PShop/classes/controller/AdminController.php(765): AdminControllerCore->processUpdateOptions() #1 /home2/crazyape/public_html/PShop/classes/controller/Controller.php(171): AdminControllerCore->postProcess() #2 /home2/crazyape/public_html/PShop/classes/Dispatcher.php(373): ControllerCore->run() #3 /home2/crazyape/public_html/PShop/admin-1495599749/index.php(54): DispatcherCore->dispatch() #4 {main} thrown in /home2/crazyape/public_html/PShop/classes/controller/AdminController.php on line 1224

The exact error is a 500 error, which gives the above error when the 500 «debunk mode» is enabled as posted in this section of the forums! If there’s any fix for this, it would be awesome if somebody could instruct me on how to do it!

Thanks in advance,

~Nick Major

Crazy Ape Computers

Hi there,

I installed PHP 7 TZS (Thread safe / pthreads) and Phalcon 3.

I putted a Phalcon Model into a class extends «Threaded»:

class ResponseObject extends Threaded {
    private $nestedObject;

    public function __construct(Model $myModel) {
        $this->nestedObject = $myModel;
    }

    public function shout() {
        echo "***** SHOUT **** (" .$this->nestedObject->getId(). ")n";
    }
}

When I call the «shout()» function above, and the script tries to get access to the «getId()» function of the Phalcon Model, I get the error below:

PHP Fatal error:  Uncaught Error: Access to undeclared static property: PhalconDi::$_default in ***/ResponseObject.php:15

Stack trace:
#0 [internal function]: PhalconDi::getDefault()
#1 ***/ResponseObject.php(15): PhalconMvcModel->unserialize('a:30:{s:4:"iiid...')
#2 ***/Response.php(39): ***/ResponseObject->shout()
#3 [internal function]: ***Response->run()
#4 {main}
thrown in ***/ResponseObject.php on line 15

I executed the function via PHP CLI

The only thing, that doesn’t work, is that the PhalconDi has problems in the run() method of the Thread.

Phalcon Methods running fine, but when the code wants to get access to Di, this error appears:

Next Error: Access to undeclared static property: PhalconDi::$_default in /***/MyResponse.php:126
Stack trace:
#0 [internal function]: PhalconDi->__construct()
#1 [internal function]: PhalconDiFactoryDefault->__construct()

Really strange. Anybody now a solution?


edited Nov ’17

Nov ’17

Pthread creates a new program context, so static di from the parent context is lost

You must implement your own DiInterface for threaded applications, even if it’s cli api. Parallel programming is a soab :P

Not quite, when a new thread is spun off, you lose some of the context of the parent thread. You should read up on that.

What you have to do, is create a DiInterface class (like FactoryDefault), which is aware of the threaded environment, and does not lose the already defined services.

pthreads requires you to use TS version of PHP binary. Personally I dislike that idea especially nowdays when we have things like nginx + ReactPHP, i.e. messing around with real threads seems too much hassle for disputable results. Even w/o ReactPHP, nginx and PhalconPHP gives absolutely superb results.

«Every time I talk about asynchronous PHP, there’s always that one person who is like “Why don’t you just use NodeJS for that?”»

;)


edited Nov ’17

Nov ’17

And from a pragmatic point of view, they are totally right. It’s cheaper in work hours to create queues and socket/tcp/http endpoints for parallel processing, even if it’s less efficient. If you want to pursue that end, you should be coding websites in ASM, or at least in C.

From krakjoe’s repo title:

Threading for PHP — Share Nothing, Do Everything :)

SHARE NOTHING. No global vars, no implicit class members. And Phalcon’s dependency injector (DiInterface) is for sharing, so the two concepts collide. Heck, they don’t just collide, they bloody crash head-on.

This article deals with a threaded file descriptor:

https://stackoverflow.com/questions/32679030/pthreads-access-to-resource-globally-in-php#answers

Note that in the answer only a string is passed into Threaded class, not the resource itself. Also note that even a simple logger requires synchronization of spawned threads.

What is the purpose of PHP? It is historically a CGI module for webservers, and that environment is NOT suitable for threaded applications. Pthreads v3 doesn’t even start in a CGI/FPM environment.

What is the purpose of Phalcon? Providing a framework for WEB applications. Phalcon was never designed to be used in threaded environments, thus the current DI is inappropriate for that.

TL;DR;

First you have to understand the problem of simple logger in a threaded environment, then you have to ask yourself: do I really want to create a wrapper class for every single service i want to use?

EDIT:

If you really want to pursue parallel programming, PHP is not for you, since it can only handle a limited number of patterns / use-cases.

I’d advise you start learning golang, it is designed from the bottom for parallel processing, and it’s core lib contains a http server which you can spin up with like 5 lines of code.

So you ended up with:

  • pthreads
  • MQ broker (zero MQ)
  • Distributed event emitter (remit)
  • PhalconPHP as a framework

Now I’m curious how will that work, are there «any» bugs out there etc.

Good luck!

With PHP CLI you have also the possibility to use Phalcon with Beanstalk queues. If you install Phalcon Incubator with composer you will have the ability to create several parallelized queues and let them process jobs. As Beanstalk is a service listening to a port, you can dispatch your workers on several servers accross a private network to balance the global load.

@mikachou: with a note that Beanstalk project unfortunately, have been abandoned.

what a pity, i didn’t know, although there has been no update on github repository since 2014

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal error yaml h no such file or directory
  • Fatal error wx setup h no such file or directory
  • Fatal error unable to open maple
  • Fatal error wordpress update
  • Fatal error unable to find local grunt

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии